5.3 函数纯度 (Function Purity)
Last updated
Last updated
A function is pure if it does not access any . Conversely, the function is impure if it does access any storage. Naturally, as storage is only available in smart contracts, impure functions cannot be used in predicates, scripts, or libraries. A pure function cannot call an impure function.
如果一个函数不访问任何,它就是 纯粹 的。反之,如果函数确实访问了任何存储,那么它就是 不纯 的。当然,由于存储只在智能合约中可用,不纯函数不能用于谓词、脚本或库中。一个纯函数不能调用一个不纯函数。
In Sway, functions are pure by default but can be opted into impurity via the storage
function attribute. The storage
attribute may take read
and/or write
arguments indicating which type of access the function requires.
在Sway中,函数默认是纯的,但可以通过storage
函数属性选择为不纯。storage
属性可以接受 read 读
和/或write 写
参数,表明该函数需要哪种类型的访问。
Note: the
#[storage(write)]
attribute also permits a function to read from storage. This is due to the fact that partially writing a storage slot requires first reading the slot. 注意:#[storage(write)]
属性也允许一个函数从存储中读取。这是由于部分写入一个存储槽需要首先读取该槽。
Impure functions which call other impure functions must have at least the same storage privileges or a superset of those for the function called. For example, to call a function with write access a caller must also have write access, or both read and write access. To call a function with read and write access the caller must also have both privileges.
调用其他不纯函数的不纯函数必须至少有相同的存储权限或被调用函数的超权限。例如,要调用一个有写权限的函数,调用者必须也有写权限,或者同时有读和写权限。要调用一个有读写权限的函数,调用者也必须有这两种权限。
The storage
attribute may also be applied to , and declarations.
储存 storage
属性也可以应用于、和的声明。
A pure function gives you some guarantees: you will not incur excessive storage gas costs, the compiler can apply additional optimizations, and they are generally easy to reason about and audit. . Note that Solidity refers to contract storage as contract state, and in the Sway/Fuel ecosystem, these two terms are largely interchangeable.
一个纯函数给你一些保证:你不会产生过多的存储气体成本,编译器可以应用额外的优化,而且它们通常容易推理和审计。。请注意,Solidity将合约存储称为 contract state,在Sway/Fuel生态系统中,这两个术语基本上是可以互换的。