4.5 函数 (Functions)
Functions in Sway are declared with the fn
keyword. Let's take a look:
Sway中的函数是用fn
关键字声明的。我们一起看一下:
We have just declared a function named equals
which takes two parameters: first_param
and second_param
. The parameters must both be 64-bit unsigned integers.
我们刚刚声明了一个名为 equals
的函数,它需要两个参数: first_param
和second_param
。这些参数必须都是64位无符号整数。
This function also returns a bool
value, i.e. either true
or false
. This function returns true
if the two given parameters are equal, and false
if they are not. If we want to use this function, we can do so like this:
这个函数还返回一个bool
值,即true
或false
。如果给定的两个参数相等,该函数返回true
,如果不相等,则返回false
。如果我们想使用这个函数,可以这样做:
可变参数 (Mutable Parameters)
We can make a function parameter mutable by adding ref mut
before the parameter name. This allows mutating the argument passed into the function when the function is called. For example:
我们可以通过在参数名称前添加ref mut
来使一个函数参数变得可变。这允许在函数被调用时,对传递到函数中的参数进行变化。例如:
This function is allowed to mutate its parameter num
because of the mut
keyword. In addition, the ref
keyword instructs the function to modify the argument passed to it when the function is called, instead of modifying a local copy of it.
这个函数被允许修改其参数num
,因为有mut
关键字。此外,ref
关键字指示该函数在调用时修改传递给它的参数,而不是修改它的本地副本。
Note that the variable num
itself has to be declared as mutable for the above to compile.
注意,变量num
本身必须被声明为可变的,这样才能编译上述内容。
Note It is not currently allowed to use
mut
withoutref
or vice versa for a function parameter.
Similarly, ref mut
can be used with more complex data types such as:
同样,ref mut
可以用于更复杂的数据类型,如:
We can then call these functions as shown below:
然后,我们可以按照下面的方式调用这些函数:
Note The only place, in a Sway program, where the
ref
keyword is valid is before a mutable function parameter.注意在Sway程序中,
ref
关键字唯一有效的地方是在可变函数参数之前。
Last updated