Introduction

Welcome to Move, a next generation language for secure, sandboxed, and formally verified programming. Its first use case is for the Diem blockchain, where Move provides the foundation for its implementation. Move allows developers to write programs that flexibly manage and transfer assets, while providing the security and protections against attacks on those assets. However, Move has been developed with use cases in mind outside a blockchain context as well.

Move takes its cue from Rust by using resource types with move (hence the name) semantics as an explicit representation of digital assets, such as currency.

介绍

欢迎使用 Move,这是一种用于安全、沙盒和形式化验证的下一代编程语言。 它的第一个用例是 Diem 区块链,Move 为其实现提供了基础。 Move 允许开发人员编写灵活地管理和转移资产的程序,同时提供安全保护,防止那些对资产攻击的行为。 不仅如此,Move 也可用于区块链之外的开发场景。

Move 的诞生从 Rust 中的*所有权(ownership)机制汲取了灵感,通过使用具有移动(move)*语义的资源类型作为数字资产(例如货币)的显示表示,Move 也因此而得名。

Who is Move for?

Move was designed and created as a secure, verified, yet flexible programming language. The first use of Move is for the implementation of the Diem blockchain. That said, the language is still evolving. Move has the potential to be a language for other blockchains, and even non-blockchain use cases as well.

Given custom Move modules will not be supported at the launch of the Diem Payment Network (DPN), we are targeting an early Move Developer persona.

The early Move Developer is one with some programming experience, who wants to begin understanding the core programming language and see examples of its usage.

Move 是为谁而准备的?

Move 被设计和创建为一种安全、经过验证且灵活的编程语言。 Move 的第一个用途是实现 Diem 区块链。也就是说,语言仍在不断发展。 Move 有可能成为其他区块链甚至非区块链用例的语言。

鉴于在 Diem 支付网络 (DPN) 启动时将不支持自定义 Move 模块,我们的目标是早期的 Move 开发人员。

早期的 Move 开发人员是具有一定编程经验的人,他们希望开始了解核心编程语言并查看其使用示例。

Hobbyists

Understanding that the capability to create custom modules on the Diem Payment Network will not be available at launch, the hobbyist Move Developer is interested in learning the intricacies of the language. She will understand the basic syntax, the standard libraries available, and write example code that can be executed using the Move CLI. The Move Developer may even want to dig into understanding how the Move Virtual Machine executes the code she writes.

爱好者

了解在 Diem 支付网络上创建自定义模块的功能在发布时将不可用,爱好 Move 的开发人员有兴趣学习该语言的复杂性。 她将了解基本语法、可用的标准库,并编写可以使用 Move CLI 执行的示例代码。 Move 开发人员甚至可能想深入了解 Move 虚拟机如何执行她编写的代码。

Core Contributor

Beyond a hobbyist wanting to stay ahead of the curve for the core programming language is someone who may want to contribute directly to Move. Whether this includes submitting language improvements or even, in the future, adding core modules available on the Diem Payment Network, the core contributor will understand Move at a deep level.

核心贡献者

除了想要在核心编程语言方面保持领先的业余爱好者之外,还有可能想要直接为 Move 做出贡献的人。 无论这包括提交语言改进,还是将来添加 Diem 支付网络上可用的核心模块,核心贡献者都将深入了解 Move。

Who Move is currently not targeting

Currently, Move is not targeting developers who wish to create custom modules and contracts for use on the Diem Payment Network. We are also not targeting novice developers who expect a completely polished developer experience even in testing the language.

Move 目前不适用于哪些人

目前,Move 不针对希望创建自定义模块和合约以在 Diem 支付网络上使用的开发人员。 我们也不针对那些期望在语言测试阶段就获得完美开发体验的新手开发者。

Where Do I Start?

Begin with understanding modules and scripts and then work through the Move Tutorial.

我该从哪里开始呢?

从了解模块和脚本开始,然后完成Move 教程。

模块和脚本

Move 有两种不同类型的程序:模块(Module)和脚本(Script)。模块是定义结构类型以及对这些类型进行操作的函数的库。结构类型定义了 Move 的全局存储的模式,模块函数定义了更新存储的规则。模块本身也存储在全局存储中。脚本是可执行文件的入口点,类似于传统语言中的主函数 main。脚本通常调用已发布模块的函数来更新全局存储。脚本是临时代码片段,不会发布在全局存储中。

一个 Move 源文件(或编译单元)可能包含多个模块和脚本。然而,发布模块或执行脚本都是独立的虚拟机(VM)操作。

语法

脚本

脚本具有以下结构:

script {
    <use>*
    <constants>*
    fun <identifier><[type parameters: constraint]*>([identifier: type]*) <function_body>
}

一个 script 块必须以它的所有 use 声明开头,然后是常量(constant)声明,最后是主函数声明。主函数的名称可以是任意的(也就是说,它不一定命名为 main),它是脚本块中唯一的函数,可以有任意数量的参数,并且不能有返回值。下面是每个组件的示例:

script {
    // 导入在命名账户地址 std 上发布的 debug 模块。
    use std::debug;

    const ONE: u64 = 1;

    fun main(x: u64) {
        let sum = x + ONE;
        debug::print(&sum)
    }
}

脚本(Script)的功能非常有限 —— 它们不能声明友元(friend)、结构类型或访问全局存储。他们的主要作用主要是调用模块函数。

模块

模块具有以下结构:

module <address>::<identifier> {
    (<use> | <friend> | <type> | <function> | <constant>)*
}

其中 <address> 是一个有效的命名或字面量地址。

例子:

module 0x42::test {
    struct Example has copy, drop { i: u64 }

    use std::debug;
    friend 0x42::another_test;

    const ONE: u64 = 1;

    public fun print(x: u64) {
        let sum = x + ONE;
        let example = Example { i: sum };
        debug::print(&sum)
    }
}

module 0x42::test 这部分指定模块 test 将在全局存储的账户地址 0x42 下发布。

模块也可以使用命名地址来声明,例如:

module test_addr::test {
    struct Example has copy, drop { a: address }

    use std::debug;
    friend test_addr::another_test;

    public fun print() {
        let example = Example { a: @test_addr };
        debug::print(&example)
    }
}

因为命名地址只存在于源语言级别和编译期间,所以命名地址将在字节码级别彻底替换它们的值。例如,如果我们有以下代码:

script {
    fun example() {
        my_addr::m::foo(@my_addr);
    }
}

我们在把 my_addr 设置为 0xC0FFEE 的情况下编译它,那么它在操作上等同于以下内容:

script {
    fun example() {
        0xC0FFEE::m::foo(@0xC0FFEE);
    }
}

然而,在源代码级别,这些是不等价的 —— 函数 m::foo 必须通过 my_addr 命名地址来访问,而不是通过分配给该地址的数值来访问。

模块名称可以以字母 a 到 z 或字母 A 到 Z 开头。在第一个字符之后,模块名可以包含下划线 _、字母 a 到 z、字母 A 到 Z 或数字 0 到 9。

module my_module {}
module foo_bar_42 {}

通常,模块名称以小写字母开头。名为 my_module 的模块应该存储在名为 my_module.move 的源文件中。

module 块内的所有元素都可以按任意顺序出现。从根本上说,模块是类型(type)和函数(function)的集合。use 关键字用来从其他模块导入类型。friend 关键字指定一个可信的模块列表。const 关键字定义了可以在模块函数中使用的私有常量。

Move 教程(Move Tutorial)

Integers

Move supports three unsigned integer types: u8, u64, and u128. Values of these types range from 0 to a maximum that depends on the size of the type.

整数

Move 支持三种无符号整数类型:u8、u64 和 u128。这些类型的值范围从 0 到最大值,具体取决于类型的大小。

TypeValue Range
Unsigned 8-bit integer, u80 to 28 - 1
Unsigned 64-bit integer, u640 to 264 - 1
Unsigned 128-bit integer, u1280 to 2128 - 1

Literals

Literal values for these types are specified either as a sequence of digits (e.g.,112) or as hex literals, e.g., 0xFF. The type of the literal can optionally be added as a suffix, e.g., 112u8. If the type is not specified, the compiler will try to infer the type from the context where the literal is used. If the type cannot be inferred, it is assumed to be u64.

If a literal is too large for its specified (or inferred) size range, an error is reported.

字面量

这些类型的文字值指定为数字序列(例如,112)或十六进制文字,例如,0xFF。可以选择将文字的类型添加为后缀,例如 112u8。如果未指定类型,编译器将尝试从使用文字的上下文推断类型。如果无法推断类型,则假定为 u64。

如果文字对于其指定的(或推断的)大小范围来说太大,则会报告错误。

Examples

例子

// literals with explicit annotations;
let explicit_u8 = 1u8;
let explicit_u64 = 2u64;
let explicit_u128 = 3u128;

// literals with simple inference
let simple_u8: u8 = 1;
let simple_u64: u64 = 2;
let simple_u128: u128 = 3;

// literals with more complex inference
let complex_u8 = 1; // inferred: u8
// right hand argument to shift must be u8
let _unused = 10 << complex_u8;

let x: u8 = 0;
let complex_u8 = 2; // inferred: u8
// arguments to `+` must have the same type
let _unused = x + complex_u8;

let complex_u128 = 3; // inferred: u128
// inferred from function argument type
function_that_takes_u128(complex_u128);

// literals can be written in hex
let hex_u8: u8 = 0x1;
let hex_u64: u64 = 0xCAFE;
let hex_u128: u128 = 0xDEADBEEF;

Operations

Arithmetic

Each of these types supports the same set of checked arithmetic operations. For all of these operations, both arguments (the left and right side operands) must be of the same type. If you need to operate over values of different types, you will need to first perform a cast. Similarly, if you expect the result of the operation to be too large for the integer type, perform a cast to a larger size before performing the operation.

All arithmetic operations abort instead of behaving in a way that mathematical integers would not (e.g., overflow, underflow, divide-by-zero).

运营

算术

这些类型中的每一种都支持相同的检查算术运算集。对于所有这些操作,两个参数(左侧和右侧操作数)必须是同一类型。如果您需要对不同类型的值进行操作,则需要首先执行强制转换。同样,如果您预计运算结果对于整数类型来说太大,请在执行运算之前执行转换为更大的大小。

所有算术运算都会中止,而不是以数学整数不会的方式表现(例如,上溢、下溢、被零除)。

SyntaxOperationAborts If
+additionResult is too large for the integer type
-subtractionResult is less than zero
*multiplicationResult is too large for the integer type
%modular divisionThe divisor is 0
/truncating divisionThe divisor is 0

Bitwise

The integer types support the following bitwise operations that treat each number as a series of individual bits, either 0 or 1, instead of as numerical integer values.

Bitwise operations do not abort.

按位

整数类型支持以下按位运算,将每个数字视为一系列单独的位,0 或 1,而不是数字整数值。

按位运算不会中止。

SyntaxOperationDescription
&bitwise andPerforms a boolean and for each bit pairwise
``bitwise or
^bitwise xorPerforms a boolean exclusive or for each bit pairwise

Bit Shifts

Similar to the bitwise operations, each integer type supports bit shifts. But unlike the other operations, the righthand side operand (how many bits to shift by) must always be a u8 and need not match the left side operand (the number you are shifting).

Bit shifts can abort if the number of bits to shift by is greater than or equal to 8, 64, or 128 for u8, u64, and u128 respectively.

位移

与按位运算类似,每种整数类型都支持位移。但与其他操作不同,右侧操作数(要移位多少位)必须始终是 u8 并且不需要匹配左侧操作数(您要移位的数字)。

如果要移位的位数分别大于或等于 u8、u64 和 u128 的 8、64 或 128,则移位可以中止。

SyntaxOperationAborts if
<<shift leftNumber of bits to shift by is greater than the size of the integer type
>>shift rightNumber of bits to shift by is greater than the size of the integer type

Comparisons

Integer types are the only types in Move that can use the comparison operators. Both arguments need to be of the same type. If you need to compare integers of different types, you will need to cast one of them first.

Comparison operations do not abort.

比较

整数类型是 Move 中唯一可以使用比较运算符的类型。两个参数必须是同一类型。如果您需要比较不同类型的整数,则需要先转换其中一个。

比较操作不会中止。

SyntaxOperation
<less than
>greater than
<=less than or equal to
>=greater than or equal to

Equality

Like all types with drop in Move, all integer types support the "equal" and "not equal" operations. Both arguments need to be of the same type. If you need to compare integers of different types, you will need to cast one of them first.

Equality operations do not abort.

平等

与 Move 中的所有类型一样,所有整数类型都支持“等于”和“不等于”操作。两个参数必须是同一类型。如果您需要比较不同类型的整数,则需要先转换其中一个。

平等操作不会中止。

SyntaxOperation
==equal
!=not equal

For more details see the section on equality

有关更多详细信息,请参阅平等部分

Casting

Integer types of one size can be cast to integer types of another size. Integers are the only types in Move that support casting.

Casts do not truncate. Casting will abort if the result is too large for the specified type

铸件

一种大小的整数类型可以转换为另一种大小的整数类型。整数是 Move 中唯一支持强制转换的类型。

强制转换不会截断。如果结果对于指定类型来说太大,则转换将中止

SyntaxOperationAborts if
(e as T)Cast integer expression e into an integer type Te is too large to represent as a T

Here, the type of e must be u8, u64, or u128 and T must be u8, u64, or u128.

For example:

这里,e 的类型必须是 u8、u64 或 u128,T 必须是 u8、u64 或 u128。

例如:

  • (x as u8)
  • (2u8 as u64)
  • (1 + 3 as u128)

Ownership

As with the other scalar values built-in to the language, integer values are implicitly copyable, meaning they can be copied without an explicit instruction such as copy.

所有权

与语言内置的其他标量值一样,整数值是隐式可复制的,这意味着它们可以在没有显式指令(如复制)的情况下复制。

Bool

bool is Move's primitive type for boolean true and false values.

布尔

bool 是 Move 的布尔真假值的原始类型。

Literals

Literals for bool are either true or false.

字面量

bool 的文字为真或假。

Operations

Logical

bool supports three logical operations:

操作符

逻辑的

bool 支持三种逻辑运算:

SyntaxDescriptionEquivalent Expression
&&short-circuiting logical andp && q is equivalent to if (p) q else false
||short-circuiting logical orp || q is equivalent to if (p) true else q
!logical negation!p is equivalent to if (p) false else true

Control Flow

bool values are used in several of Move's control-flow constructs:

控制流

布尔值用于 Move 的多个控制流结构中:

Ownership

As with the other scalar values built-in to the language, boolean values are implicitly copyable, meaning they can be copied without an explicit instruction such as copy.

所有权

与语言内置的其他标量值一样,布尔值是隐式可复制的,这意味着它们可以在没有显式指令(如复制)的情况下复制。

地址

地址(address)是 Move 中的内置类型,用于表示全局存储中的的位置(有时称为账户)。地址(address) 值是一个 128 位(16 字节)标识符。在一个给定的地址,可以存储两样东西:模块(Module)和资源(Resources)。

虽然地址(address)在底层是一个 128 位整数,但 Move 语言有意让其不透明 —— 它们不能从整数创建,不支持算术运算,也不能修改。即使可能有一些有趣的程序会使用这种特性(例如,C 中的指针算法实现了类似壁龛(niche)的功能),但 Move 语言不允许这种动态行为,因为它从头开始就被设计为支持静态验证。(壁龛指安装在墙壁上的小格子或在墙身上留出的作为贮藏设施的空间,最早在宗教上是指排放佛像的小空间,现在多用在家庭装修上,因其不占建筑面积,使用比较方便,深受大家喜爱,Joe 注)

你可以通过运行时地址值(address 类型的值)来访问该地址处的资源。但无法在运行时通过地址值访问模块。

地址及其语法

地址有两种形式:命名的或数值的。命名地址的语法遵循 Move 命名标识符的规则。数值地址的语法不受十六进制编码值的限制,任何有效的 u128 数值都可以用作地址值。例如,42,0xCFAE 和 2021 都是合法有效的数值地址字面量(literal)。

为了区分何时在表达式上下文中使用地址,使用地址时的语法根据使用地址的上下文而有所不同:

  • 当地址被用作表达式时,地址必须以 @ 字符为前缀,例如:@<numerical_value> 或 @<named_address_identifier>。
  • 在表达式上下文之外,地址可以不带前缀字符 @。例如:<numerical_value> 或 <named_address_identifier>。

通常,可以将 @ 视为将地址从命名空间项变为表达式项的运算符。

命名地址

命名地址是一项特性,它允许在使用地址的任何地方使用标识符代替数值,而不仅仅是在值级别。命名地址被声明并绑定为 Move 包中的顶级元素(模块和脚本之外)或作为参数传递给 Move 编译器。

命名地址仅存在于源语言级别,并将在字节码级别完全替代它们的值。因此,模块和模块成员必须通过模块的命名地址而不是编译期间分配给命名地址的数值来访问,例如:use my_addr::foo 不等于 use 0x2::foo,即使 Move 程序编译时将 my_addr 设置成 0x2。这个区别在模块和脚本一节中有更详细的讨论。

例子

let a1: address = @0x1; // 0x00000000000000000000000000000001 的缩写
let a2: address = @0x42; // 0x00000000000000000000000000000042 的缩写
let a3: address = @0xDEADBEEF; // 0x000000000000000000000000DEADBEEF 的缩写
let a4: address = @0x0000000000000000000000000000000A;
let a5: address = @std; // 将命名地址 `std` 的值赋给 `a5`
let a6: address = @66;
let a7: address = @0x42;

module 66::some_module {   // 不在表达式上下文中,所以不需要 @
    use 0x1::other_module; // 不在表达式上下文中,所以不需要 @
    use std::vector;       // 使用其他模块时,可以使用命名地址作为命名空间项
    ...
}

module std::other_module {  // 可以使用命名地址作为命名空间项来声明模块
    ...
}

全局存储操作

address 值主要用来与全局存储操作进行交互。

address 值与 exists、borrow_global、borrow_global_mut 和 move_from 操作(operation)一起使用。

唯一不使用 address 的全局存储操作是 move_to,它使用了 signer。

所有权

与 Move 语言内置的其他标量值一样,address 值是隐式可复制的,这意味着它们可以在没有显式指令(例如 copy)的情况下复制。

向量

vector<T> 是 Move 提供的唯一原始集合类型。vector<T> 是类型为 T 的同构集合,可以通过从"末端"推入/弹出(出栈/入栈,译者注)值来增长或缩小。 (与 Rust 一样,向量(vector)是一种可以存放任何类型的可变大小的容器,也可称为动态数组,与 Python 中的列表(list)不同,译者注)

vector<T> 可以用任何类型 T 实例化。例如,vector<u64>、vector<address>、vector<0x42::MyModuel::MyResource> 和 vector<vector<u8>> 都是有效的向量类型。

字面量

通用 vector 字面量

任何类型的向量都可以通过 vector 字面量创建。

语法类型描述
vector[]vector[]: vector<T> 其中 T 是任何单一的非引用类型一个空向量
vector[e1, ..., en]vector[e1, ..., en]: vector<T> where e_i: T 满足 0 < i <= n and n > 0带有 n 个元素(长度为 n)的向量

在这些情况下,vector 的类型是从元素类型或从向量的使用上推断出来的。如果无法推断类型或者只是为了更清楚地表示,则可以显式指定类型:

vector<T>[]: vector<T>
vector<T>[e1, ..., en]: vector<T>

向量字面量示例

(vector[]: vector<bool>);
(vector[0u8, 1u8, 2u8]: vector<u8>);
(vector<u128>[]: vector<u128>);
(vector<address>[@0x42, @0x100]: vector<address>);

vector<u8> 字面量

Move 中向量的一个常见用例是表示“字节数组”,用 vector<u8> 表示。这些值通常用于加密目的,例如公钥或哈希结果。这些值非常常见,以至于提供了特定的语法以使值更具可读性,而不是必须使用 vector[],其中每个单独的 u8 值都以数字形式指定。

目前支持两种类型的 vector<u8> 字面量,字节字符串和十六进制字符串。

字节字符串

字节字符串是带引号的字符串字面量,以 b 为前缀,例如,b"Hello!\n"。

这些是允许转义序列的 ASCII 编码字符串。目前,支持的转义序列如下:

转义序列描述
\n换行
\r回车
\t制表符
\\反斜杠
\0Null
\"引号
\xHH十六进制进制转义,插入十六进制字节序列 HH

十六进制字符串

十六进制字符串是以 x 为前缀的带引号的字符串字面量,例如,x"48656C6C6F210A"。

每个字节对,范围从 00 到 FF 都被解析为十六进制编码的 u8 值。所以每个字节对对应于结果 vector<u8> 的单个条目。

字符串字面量示例

script {
    fun byte_and_hex_strings() {
        assert!(b"" == x"", 0);
        assert!(b"Hello!\n" == x"48656C6C6F210A", 1);
        assert!(b"\x48\x65\x6C\x6C\x6F\x21\x0A" == x"48656C6C6F210A", 2);
        assert!(
            b"\"Hello\tworld!\"\n \r \\Null=\0" ==
                x"2248656C6C6F09776F726C6421220A200D205C4E756C6C3D00",
            3
        );
    }
}

操作

vector 通过 Move 标准库里的 std::vector 模块支持以下操作:

函数描述中止条件
vector::empty<T>(): vector<T>创建一个可以存储 T 类型值的空向量永不中止
vector::singleton<T>(t: T): vector<T>创建一个包含 t 的大小为 1 的向量永不中止
vector::push_back<T>(v: &mut vector<T>, t: T)将 t 添加到 v 的尾部永不中止
vector::pop_back<T>(v: &mut vector<T>): T移除并返回 v 中的最后一个元素如果 v 是空向量
vector::borrow<T>(v: &vector<T>, i: u64): &T返回在索引 i 处对 T 的不可变引用如果 i 越界
vector::borrow_mut<T>(v: &mut vector<T>, i: u64): &mut T返回在索引 i 处对 T 的可变引用如果 i 越界
vector::destroy_empty<T>(v: vector<T>)销毁 v 向量如果 v 不是空向量
vector::append<T>(v1: &mut vector<T>, v2: vector<T>)将 v2 中的元素添加到 v1 的末尾永不中止
vector::contains<T>(v: &vector<T>, e: &T): bool如果 e 在向量 v 里返回 true,否则返回 false永不中止
vector::swap<T>(v: &mut vector<T>, i: u64, j: u64)交换向量 v 中第 i 个和第 j 个索引处的元素如果 i 或 j 越界
vector::reverse<T>(v: &mut vector<T>)反转向量 v 中元素的顺序永不中止
vector::index_of<T>(v: &vector<T>, e: &T): (bool, u64)如果 e 在索引 i 处的向量中,则返回 (true, i)。否则返回(false, 0)永不中止
vector::remove<T>(v: &mut vector<T>, i: u64): T移除向量 v 中的第 i 个元素,移动所有后续元素。这里的时间复杂度是 O(n),并且保留了向量中元素的顺序如果 i 越界
vector::swap_remove<T>(v: &mut vector<T>, i: u64): T将向量中的第 i 个元素与最后一个元素交换,然后弹出该元素。这里的时间复杂度是 O(1),但是不保留向量中的元素顺序如果 i 越界

随着时间的推移可能会增加更多操作。

示例

use std::vector;

let v = vector::empty<u64>();
vector::push_back(&mut v, 5);
vector::push_back(&mut v, 6);

assert!(*vector::borrow(&v, 0) == 5, 42);
assert!(*vector::borrow(&v, 1) == 6, 42);
assert!(vector::pop_back(&mut v) == 6, 42);
assert!(vector::pop_back(&mut v) == 5, 42);

销毁和复制 vector

vector<T> 的某些行为取决于元素类型 T 的能力(ability),例如:如果向量中包含不具有 drop 能力的元素,那么不能像上面例子中的 v 一样隐式丢弃 —— 它们必须用 vector::destroy_empty 显式销毁。

请注意,除非向量 vec 包含零个元素,否则 vector::destroy_empty 将在运行时中止:

fun destroy_any_vector<T>(vec: vector<T>) {
    vector::destroy_empty(vec) // 删除此行将导致编译器错误
}

但是删除包含带有 drop 能力的元素的向量不会发生错误:

fun destroy_droppable_vector<T: drop>(vec: vector<T>) {
    // 有效!
    // 不需要明确地做任何事情来销毁向量
}

同样,除非元素类型具有 copy 能力,否则无法复制向量。换句话说,当且仅当 T 具有 copy 能力时,vector<T> 才具有 copy 能力。然而,即使是可复制的向量也永远不会被隐式复制:

let x = vector::singleton<u64>(10);
let y = copy x; // 没有 copy 将导致编译器错误!

大向量的复制可能很昂贵,因此编译器需要显式 copy 以便更容易查看它们发生的位置。

有关更多详细信息,请参阅类型能力和泛型部分。

所有权

如上所述,vector 值只有在元素值可以复制的时候才能复制。在这种情况下,复制必须通过显式 copy 或者解引用 *。

签名者

签名者(signer)是 Move 内置的资源类型。签名者(signer)是一种允许持有者代表特定地址(address)行使权力的能力(capability)。你可以将原生实现(native implementation)视为:

struct signer has drop { a: address }

signer 有点像 Unix UID,因为它表示一个通过 Move 之外的代码(例如,通过检查加密签名或密码)进行身份验证的用户。

与 address 的比较

Move 程序可以使用地址字面量(literal)创建任何地址(address)值,而无需特殊许可:

let a1 = @0x1;
let a2 = @0x2;
// ... 等等,所有其他可能的地址

但是,signer 值是特殊的,因为它们不能通过字面量或者指令创建 —— 只能通过 Move 虚拟机(VM)创建。在虚拟机运行带有 signer 类型参数的脚本之前,它会自动创建 signer 值并将它们传递给脚本:

script {
    use std::signer;
    fun main(s: signer) {
        assert!(signer::address_of(&s) == @0x42, 0);
    }
}

如果脚本是从 0x42 以外的任何地址发送的,则此脚本将中止并返回代码 0。

交易脚本可以有任意数量的 signer,只要 signer 参数排在其他参数前面。换句话说,所有 signer 参数都必须放在第一位。

script {
    use std::signer;
    fun main(s1: signer, s2: signer, x: u64, y: u8) {
        // ...
    }
}

这对于实现具有多方权限原子行为的*多重签名脚本(multi-signer scripts)*很有用。例如,上述脚本的扩展可以在 s1 和 s2 之间执行原子货币交换。

signer 操作符

std::signer 标准库模块为 signer 提供了两个实用函数:

函数描述
signer::address_of(&signer): address返回由 &signer 包装的地址值。
signer::borrow_address(&signer): &address返回由 &signer 包装的地址的引用。

此外,move_to<T>(&signer, T) 全局存储操作符需要一个 &signer 参数在 signer.address 的帐户下发布资源 T。这确保了只有经过身份验证的用户才能在其地址下发布资源。

所有权

与简单的标量值不同,signer 值是不可复制的,这意味着他们不能被复制(通过任何操作,无论是通过显式 copy指令还是通过解引用(dereference)*)。

References

Move has two types of references: immutable & and mutable &mut. Immutable references are read only, and cannot modify the underlying value (or any of its fields). Mutable references allow for modifications via a write through that reference. Move's type system enforces an ownership discipline that prevents reference errors.

For more details on the rules of references, see Structs and Resources

参考

Move 有两种类型的引用:不可变的 & 和可变的 &mut。不可变引用是只读的,不能修改基础值(或其任何字段)。可变引用允许通过写入该引用进行修改。 Move 的类型系统强制执行防止引用错误的所有权规则。

有关引用规则的更多详细信息,请参阅结构和资源

Reference Operators

Move provides operators for creating and extending references as well as converting a mutable reference to an immutable one. Here and elsewhere, we use the notation e: T for "expression e has type T".

引用运算符

Move 提供了用于创建和扩展引用以及将可变引用转换为不可变引用的运算符。在这里和其他地方,我们使用符号 e: T 来表示“表达式 e 具有类型 T”。

SyntaxTypeDescription
&e&T where e: T and T is a non-reference typeCreate an immutable reference to e
&mut e&mut T where e: T and T is a non-reference typeCreate a mutable reference to e.
&e.f&T where e.f: TCreate an immutable reference to field f of struct e.
&mut e.f&mut T where e.f: TCreate a mutable reference to field f of structe.
freeze(e)&T where e: &mut TConvert the mutable reference e into an immutable reference.

The &e.f and &mut e.f operators can be used both to create a new reference into a struct or to extend an existing reference:

&e.f 和 &mut e.f 运算符既可用于创建对结构的新引用,也可用于扩展现有引用:

let s = S { f: 10 };
let f_ref1: &u64 = &s.f; // works
let s_ref: &S = &s;
let f_ref2: &u64 = &s_ref.f // also works

A reference expression with multiple fields works as long as both structs are in the same module:

只要两个结构都在同一个模块中,具有多个字段的引用表达式就可以工作:

struct A { b: B }
struct B { c : u64 }
fun f(a: &A): &u64 {
  &a.b.c
}

Finally, note that references to references are not allowed:

最后,请注意,不允许引用引用:

let x = 7;
let y: &u64 = &x;
let z: &&u64 = &y; // will not compile

Reading and Writing Through References

Both mutable and immutable references can be read to produce a copy of the referenced value.

Only mutable references can be written. A write *x = v discards the value previously stored in x and updates it with v.

Both operations use the C-like * syntax. However, note that a read is an expression, whereas a write is a mutation that must occur on the left hand side of an equals.

通过参考文献阅读和写作

可以读取可变和不可变引用以生成引用值的副本。

只能编写可变引用。写入 *x = v 会丢弃先前存储在 x 中的值并用 v 更新它。

这两个操作都使用类 C 的 * 语法。但是,请注意,读是一个表达式,而写是一个突变,必须发生在等号的左侧。

SyntaxTypeDescription
*eT where e is &T or &mut TRead the value pointed to by e
*e1 = e2() where e1: &mut T and e2: TUpdate the value in e1 with e2.

In order for a reference to be read, the underlying type must have the copy ability as reading the reference creates a new copy of the value. This rule prevents the copying of resource values:

为了读取引用,基础类型必须具有复制能力,因为读取引用会创建值的新副本。此规则防止复制资源值:

fun copy_resource_via_ref_bad(c: Coin) {
    let c_ref = &c;
    let counterfeit: Coin = *c_ref; // not allowed!
    pay(c);
    pay(counterfeit);
}

Dually: in order for a reference to be written to, the underlying type must have the drop ability as writing to the reference will discard (or "drop") the old value. This rule prevents the destruction of resource values: 双重:为了写入引用,基础类型必须具有删除能力,因为写入引用将丢弃(或“删除”)旧值。此规则可防止破坏资源值:

fun destroy_resource_via_ref_bad(ten_coins: Coin, c: Coin) {
    let ref = &mut ten_coins;
    *ref = c; // not allowed--would destroy 10 coins!
}

freeze inference

A mutable reference can be used in a context where an immutable reference is expected:

冻结推理

可变引用可以在需要不可变引用的上下文中使用:

let x = 7;
let y: &mut u64 = &mut x;

This works because the under the hood, the compiler inserts freeze instructions where they are needed. Here are a few more examples of freeze inference in action: 这是因为在底层,编译器会在需要的地方插入冻结指令。以下是冻结推理的更多示例:

fun takes_immut_returns_immut(x: &u64): &u64 { x }

// freeze inference on return value
fun takes_mut_returns_immut(x: &mut u64): &u64 { x }

fun expression_examples() {
    let x = 0;
    let y = 0;
    takes_immut_returns_immut(&x); // no inference
    takes_immut_returns_immut(&mut x); // inferred freeze(&mut x)
    takes_mut_returns_immut(&mut x); // no inference

    assert!(&x == &mut y, 42); // inferred freeze(&mut y)
}

fun assignment_examples() {
    let x = 0;
    let y = 0;
    let imm_ref: &u64 = &x;

    imm_ref = &x; // no inference
    imm_ref = &mut y; // inferred freeze(&mut y)
}

Subtyping

With this freeze inference, the Move type checker can view &mut T as a subtype of &T. As shown above, this means that anywhere for any expression where a &T value is used, a &mut T value can also be used. This terminology is used in error messages to concisely indicate that a &mut T was needed where a &T was supplied. For example

子类型化

通过这种冻结推断,Move 类型检查器可以将 &mut T 视为 &T 的子类型。如上所示,这意味着对于任何使用 &T 值的表达式,也可以使用 &mut T 值。此术语用于错误消息中,以简明扼要地表明在提供 &T 的情况下需要 &mut T。例如

address 0x42 {
module example {
    fun read_and_assign(store: &mut u64, new_value: &u64) {
        *store = *new_value
    }

    fun subtype_examples() {
        let x: &u64 = &0;
        let y: &mut u64 = &mut 1;

        x = &mut 1; // valid
        y = &2; // invalid!

        read_and_assign(y, x); // valid
        read_and_assign(x, y); // invalid!
    }
}
}

will yield the following error messages 将产生以下错误消息

error:

    ┌── example.move:12:9 ───
    │
 12 │         y = &2; // invalid!
    │         ^ Invalid assignment to local 'y'
    ·
 12 │         y = &2; // invalid!
    │             -- The type: '&{integer}'
    ·
  9 │         let y: &mut u64 = &mut 1;
    │                -------- Is not a subtype of: '&mut u64'
    │

error:

    ┌── example.move:15:9 ───
    │
 15 │         read_and_assign(x, y); // invalid!
    │         ^^^^^^^^^^^^^^^^^^^^^ Invalid call of '0x42::example::read_and_assign'. Invalid argument for parameter 'store'
    ·
  8 │         let x: &u64 = &0;
    │                ---- The type: '&u64'
    ·
  3 │     fun read_and_assign(store: &mut u64, new_value: &u64) {
    │                                -------- Is not a subtype of: '&mut u64'
    │

The only other types currently that has subtyping are tuples

当前唯一具有子类型的其他类型是元组

Ownership

Both mutable and immutable references can always be copied and extended even if there are existing copies or extensions of the same reference:

所有权

即使存在相同引用的现有副本或扩展,可变引用和不可变引用也始终可以被复制和扩展:

fun reference_copies(s: &mut S) {
  let s_copy1 = s; // ok
  let s_extension = &mut s.f; // also ok
  let s_copy2 = s; // still ok
  ...
}

This might be surprising for programmers familiar with Rust's ownership system, which would reject the code above. Move's type system is more permissive in its treatment of copies, but equally strict in ensuring unique ownership of mutable references before writes.

对于熟悉 Rust 所有权系统的程序员来说,这可能会令人惊讶,因为他们会拒绝上面的代码。 Move 的类型系统在处理副本方面更加宽松,但在写入前确保可变引用的唯一所有权方面同样严格。

References Cannot Be Stored

References and tuples are the only types that cannot be stored as a field value of structs, which also means that they cannot exist in global storage. All references created during program execution will be destroyed when a Move program terminates; they are entirely ephemeral. This invariant is also true for values of types without the store ability, but note that references and tuples go a step further by never being allowed in structs in the first place.

This is another difference between Move and Rust, which allows references to be stored inside of structs.

Currently, Move cannot support this because references cannot be serialized, but every Move value must be serializable. This requirement comes from Move's persistent global storage, which needs to serialize values to persist them across program executions. Structs can be written to global storage, and thus they must be serializable.

One could imagine a fancier, more expressive, type system that would allow references to be stored in structs and ban those structs from existing in global storage. We could perhaps allow references inside of structs that do not have the store ability, but that would not completely solve the problem: Move has a fairly complex system for tracking static reference safety, and this aspect of the type system would also have to be extended to support storing references inside of structs. In short, Move's type system (particularly the aspects around reference safety) would have to expand to support stored references. But it is something we are keeping an eye on as the language evolves.

无法存储引用

引用和元组是唯一不能存储为结构的字段值的类型,这也意味着它们不能存在于全局存储中。当 Move 程序终止时,程序执行期间创建的所有引用都将被销毁;它们完全是短暂的。这个不变量对于没有存储能力的类型的值也是正确的,但请注意,引用和元组更进一步,因为从一开始就不允许在结构中。

这是 Move 和 Rust 之间的另一个区别,后者允许将引用存储在结构内。

目前,Move 无法支持这一点,因为引用无法序列化,但每个 Move 值都必须是可序列化的。这个需求来自于 Move 的持久化全局存储,它需要序列化值以在程序执行中持久化它们。结构可以写入全局存储,因此它们必须是可序列化的。

可以想象一种更奇特、更有表现力的类型系统,它允许将引用存储在结构中,并禁止这些结构存在于全局存储中。我们也许可以允许不具备存储能力的结构内部的引用,但这并不能完全解决问题:Move 有一个相当复杂的系统来跟踪静态引用安全,并且类型系统的这方面也必须扩展支持在结构内存储引用。简而言之,Move 的类型系统(尤其是与引用安全相关的方面)必须扩展以支持存储的引用。但随着语言的发展,我们一直在关注这一点。

Tuples and Unit

Move does not fully support tuples as one might expect coming from another language with them as a first-class value. However, in order to support multiple return values, Move has tuple-like expressions. These expressions do not result in a concrete value at runtime (there are no tuples in the bytecode), and as a result they are very limited: they can only appear in expressions (usually in the return position for a function); they cannot be bound to local variables; they cannot be stored in structs; and tuple types cannot be used to instantiate generics.

Similarly, unit () is a type created by the Move source language in order to be expression based. The unit value () does not result in any runtime value. We can consider unit() to be an empty tuple, and any restrictions that apply to tuples also apply to unit.

It might feel weird to have tuples in the language at all given these restrictions. But one of the most common use cases for tuples in other languages is for functions to allow functions to return multiple values. Some languages work around this by forcing the users to write structs that contain the multiple return values. However in Move, you cannot put references inside of structs. This required Move to support multiple return values. These multiple return values are all pushed on the stack at the bytecode level. At the source level, these multiple return values are represented using tuples.

元组和单元

Move 不完全支持元组,因为人们可能期望来自另一种语言的元组将它们作为一等值。但是,为了支持多个返回值,Move 具有类似元组的表达式。这些表达式在运行时不会产生具体的值(字节码中没有元组),因此它们非常有限:它们只能出现在表达式中(通常在函数的返回位置);它们不能绑定到局部变量;它们不能存储在结构中;元组类型不能用于实例化泛型。

类似地,unit() 是 Move 源语言创建的一种类型,以便基于表达式。单位值 () 不会产生任何运行时值。我们可以认为 unit() 是一个空元组,适用于元组的任何限制也适用于 unit。

考虑到这些限制,在语言中使用元组可能会感觉很奇怪。但其他语言中元组最常见的用例之一是函数允许函数返回多个值。一些语言通过强制用户编写包含多个返回值的结构来解决这个问题。但是在 Move 中,您不能将引用放在结构中。这需要 Move 支持多个返回值。这些多个返回值都在字节码级别被压入堆栈。在源级别,这些多个返回值使用元组表示。

Literals

Tuples are created by a comma separated list of expressions inside of parentheses

字面量

元组由括号内的逗号分隔的表达式列表创建

SyntaxTypeDescription
()(): ()Unit, the empty tuple, or the tuple of arity 0
(e1, ..., en)(e1, ..., en): (T1, ..., Tn) where e_i: Ti s.t. 0 < i <= n and n > 0A n-tuple, a tuple of arity n, a tuple with n elements

Note that (e) does not have type (e): (t), in other words there is no tuple with one element. If there is only a single element inside of the parentheses, the parentheses are only used for disambiguation and do not carry any other special meaning.

Sometimes, tuples with two elements are called "pairs" and tuples with three elements are called "triples."

注意 (e) 没有类型 (e): (t),换句话说,没有一个元素的元组。如果括号内只有一个元素,则括号仅用于消歧,不带有任何其他特殊含义。

有时,具有两个元素的元组称为“对”,而具有三个元素的元组称为“三元组”。

Examples

例子

address 0x42 {
module example {
    // all 3 of these functions are equivalent

    // when no return type is provided, it is assumed to be `()`
    fun returs_unit_1() { }

    // there is an implicit () value in empty expression blocks
    fun returs_unit_2(): () { }

    // explicit version of `returs_unit_1` and `returs_unit_2`
    fun returs_unit_3(): () { () }


    fun returns_3_values(): (u64, bool, address) {
        (0, false, @0x42)
    }
    fun returns_4_values(x: &u64): (&u64, u8, u128, vector<u8>) {
        (x, 0, 1, b"foobar")
    }
}
}

Operations

The only operation that can be done on tuples currently is destructuring.

Destructuring

For tuples of any size, they can be destructured in either a let binding or in an assignment.

For example:

运营

目前可以对元组进行的唯一操作是解构。

解构

对于任何大小的元组,它们可以在 let 绑定或赋值中解构。

例如:

address 0x42 {
module example {
    // all 3 of these functions are equivalent
    fun returns_unit() {}
    fun returns_2_values(): (bool, bool) { (true, false) }
    fun returns_4_values(x: &u64): (&u64, u8, u128, vector<u8>) { (x, 0, 1, b"foobar") }

    fun examples(cond: bool) {
        let () = ();
        let (x, y): (u8, u64) = (0, 1);
        let (a, b, c, d) = (@0x0, 0, false, b"");

        () = ();
        (x, y) = if (cond) (1, 2) else (3, 4);
        (a, b, c, d) = (@0x1, 1, true, b"1");
    }

    fun examples_with_function_calls() {
        let () = returns_unit();
        let (x, y): (bool, bool) = returns_2_values();
        let (a, b, c, d) = returns_4_values(&0);

        () = returns_unit();
        (x, y) = returns_2_values();
        (a, b, c, d) = returns_4_values(&1);
    }
}
}

For more details, see Move Variables. 有关更多详细信息,请参阅移动变量。

Subtyping

Along with references, tuples are the only types that have subtyping in Move. Tuples do have subtyping only in the sense that subtype with references (in a covariant way).

For example

子类型化

除了引用,元组是唯一在 Move 中具有子类型的类型。元组只有在具有引用的子类型(以协变方式)的意义上才具有子类型。

例如

let x: &u64 = &0;
let y: &mut u64 = &mut 1;

// (&u64, &mut u64) is a subtype of (&u64, &u64)
//   since &mut u64 is a subtype of &u64
let (a, b): (&u64, &u64) = (x, y);
// (&mut u64, &mut u64) is a subtype of (&u64, &u64)
//   since &mut u64 is a subtype of &u64
let (c, d): (&u64, &u64) = (y, y);
// error! (&u64, &mut u64) is NOT a subtype of (&mut u64, &mut u64)
//   since &u64 is NOT a subtype of &mut u64
let (e, f): (&mut u64, &mut u64) = (x, y);

Ownership

As mentioned above, tuple values don't really exist at runtime. And currently they cannot be stored into local variables because of this (but it is likely that this feature will come soon). As such, tuples can only be moved currently, as copying them would require putting them into a local variable first.

所有权

如上所述,元组值在运行时并不真正存在。由于这个原因,目前它们不能存储到局部变量中(但这个功能很可能很快就会出现)。因此,元组目前只能移动,因为复制它们需要先将它们放入局部变量中。

Local Variables and Scope

Local variables in Move are lexically (statically) scoped. New variables are introduced with the keyword let, which will shadow any previous local with the same name. Locals are mutable and can be updated both directly and via a mutable reference.

局部变量和范围

Move 中的局部变量是词法(静态)范围的。使用关键字 let 引入了新变量,这将隐藏任何以前的同名本地变量。局部变量是可变的,可以直接更新,也可以通过可变引用更新。

Declaring Local Variables

let bindings

Move programs use let to bind variable names to values:

声明局部变量

let 绑定

移动程序使用 let 将变量名绑定到值:

let x = 1;
let y = x + x:

let can also be used without binding a value to the local.

let 也可以在不将值绑定到本地的情况下使用。

let x;

The local can then be assigned a value later.

然后可以稍后为本地分配一个值。

let x;
if (cond) {
  x = 1
} else {
  x = 0
}

This can be very helpful when trying to extract a value from a loop when a default value cannot be provided.

当无法提供默认值时,这在尝试从循环中提取值时非常有用。

let x;
let cond = true;
let i = 0;
loop {
    (x, cond) = foo(i);
    if (!cond) break;
    i = i + 1;
}

Variables must be assigned before use

Move's type system prevents a local variable from being used before it has been assigned.

变量必须在使用前赋值

Move 的类型系统防止在分配之前使用局部变量。

let x;
x + x // ERROR!
let x;
if (cond) x = 0;
x + x // ERROR!
let x;
while (cond) x = 0;
x + x // ERROR!

Valid variable names

Variable names can contain underscores _, letters a to z, letters A to Z, and digits 0 to 9. Variable names must start with either an underscore _ or a letter a through z. They cannot start with uppercase letters.

有效的变量名

变量名称可以包含下划线 _、字母 a 到 z、字母 A 到 Z 以及数字 0 到 9。变量名称必须以下划线 _ 或字母 a 到 z 开头。它们不能以大写字母开头。

// all valid
let x = e;
let _x = e;
let _A = e;
let x0 = e;
let xA = e;
let foobar_123 = e;

// all invalid
let X = e; // ERROR!
let Foo = e; // ERROR!

Type annotations

The type of a local variable can almost always be inferred by Move's type system. However, Move allows explicit type annotations that can be useful for readability, clarity, or debuggability. The syntax for adding a type annotation is:

类型注释

局部变量的类型几乎总是可以通过 Move 的类型系统推断出来。但是,Move 允许显式类型注释,这对可读性、清晰性或可调试性很有用。添加类型注释的语法是:

let x: T = e; // "Variable x of type T is initialized to expression e"

Some examples of explicit type annotations:

显式类型注释的一些示例:

address 0x42 {
module example {

    struct S { f: u64, g: u64 }

    fun annotated() {
        let u: u8 = 0;
        let b: vector<u8> = b"hello";
        let a: address = @0x0;
        let (x, y): (&u64, &mut u64) = (&0, &mut 1);
        let S { f, g: f2 }: S = S { f: 0, g: 1 };
    }
}
}

Note that the type annotations must always be to the right of the pattern:

请注意,类型注释必须始终位于模式的右侧:

let (x: &u64, y: &mut u64) = (&0, &mut 1); // ERROR! should be let (x, y): ... =

When annotations are necessary

In some cases, a local type annotation is required if the type system cannot infer the type. This commonly occurs when the type argument for a generic type cannot be inferred. For example:

需要注释时

在某些情况下,如果类型系统无法推断类型,则需要本地类型注释。当无法推断泛型类型的类型参数时,通常会发生这种情况。例如:

let _v1 = vector::empty(); // ERROR!
//        ^^^^^^^^^^^^^^^ Could not infer this type. Try adding an annotation
let v2: vector<u64> = vector::empty(); // no error

In a rarer case, the type system might not be able to infer a type for divergent code (where all the following code is unreachable). Both return and abort are expressions and can have any type. A loop has type () if it has a break, but if there is no break out of the loop, it could have any type. If these types cannot be inferred, a type annotation is required. For example, this code:

在极少数情况下,类型系统可能无法推断不同代码的类型(以下所有代码都无法访问)。 return 和 abort 都是表达式,可以有任何类型。如果循环有中断,则其类型为 (),但如果循环没有中断,则它可以具有任何类型。如果无法推断出这些类型,则需要类型注释。例如,这段代码:

let a: u8 = return ();
let b: bool = abort 0;
let c: signer = loop ();

let x = return (); // ERROR!
//  ^ Could not infer this type. Try adding an annotation
let y = abort 0; // ERROR!
//  ^ Could not infer this type. Try adding an annotation
let z = loop (); // ERROR!
//  ^ Could not infer this type. Try adding an annotation

Adding type annotations to this code will expose other errors about dead code or unused local variables, but the example is still helpful for understanding this problem.

在这段代码中添加类型注释会暴露其他关于死代码或未使用的局部变量的错误,但该示例仍然有助于理解这个问题。

Multiple declarations with tuples

let can introduce more than one local at a time using tuples. The locals declared inside the parenthesis are initialized to the corresponding values from the tuple.

带有元组的多个声明

let 可以使用元组一次引入多个本地。括号内声明的局部变量被初始化为元组中的相应值。

let () = ();
let (x0, x1) = (0, 1);
let (y0, y1, y2) = (0, 1, 2);
let (z0, z1, z2, z3) = (0, 1, 2, 3);

The type of the expression must match the arity of the tuple pattern exactly.

表达式的类型必须与元组模式的数量完全匹配。

let (x, y) = (0, 1, 2); // ERROR!
let (x, y, z, q) = (0, 1, 2); // ERROR!

You cannot declare more than one local with the same name in a single let. 您不能在一个 let 中声明多个具有相同名称的本地。

let (x, x) = 0; // ERROR!

Multiple declarations with structs

let can also introduce more than one local at a time when destructuring (or matching against) a struct. In this form, the let creates a set of local variables that are initialized to the values of the fields from a struct. The syntax looks like this:

带有结构的多个声明

let 还可以在解构(或匹配)结构时一次引入多个本地。在这种形式中,let 创建了一组局部变量,这些变量被初始化为结构中字段的值。语法如下所示:

struct T { f1: u64, f2: u64 }
let T { f1: local1, f2: local2 } = T { f1: 1, f2: 2 };
// local1: u64
// local2: u64

Here is a more complicated example:

这是一个更复杂的例子:

address 0x42 {
module example {
    struct X { f: u64 }
    struct Y { x1: X, x2: X }

    fun new_x(): X {
        X { f: 1 }
    }

    fun example() {
        let Y { x1: X { f }, x2 } = Y { x1: new_x(), x2: new_x() };
        assert!(f + x2.f == 2, 42);

        let Y { x1: X { f: f1 }, x2: X { f: f2 } } = Y { x1: new_x(), x2: new_x() };
        assert!(f1 + f2 == 2, 42);
    }
}
}

Fields of structs can serve double duty, identifying the field to bind and the name of the variable. This is sometimes referred to as punning. 结构的字段可以起到双重作用,识别要绑定的字段和变量的名称。这有时被称为双关语。

let X { f } = e;

is equivalent to:

相当于:

let X { f: f } = e;

As shown with tuples, you cannot declare more than one local with the same name in a single let.

如元组所示,您不能在单个 let 中声明多个具有相同名称的本地。

let Y { x1: x, x2: x } = e; // ERROR!

Destructuring against references

In the examples above for structs, the bound value in the let was moved, destroying the struct value and binding its fields.

针对引用进行解构

在上面的结构示例中,let 中的绑定值被移动,破坏了结构值并绑定了它的字段。

struct T { f1: u64, f2: u64 }
let T { f1: local1, f2: local2 } = T { f1: 1, f2: 2 };
// local1: u64
// local2: u64

In this scenario the struct value T { f1: 1, f2: 2 } no longer exists after the let.

If you wish instead to not move and destroy the struct value, you can borrow each of its fields. For example: 在这种情况下,结构值 T { f1: 1, f2: 2 } 在 let 之后不再存在。

如果您希望不移动和破坏结构值,则可以借用其每个字段。例如:

let t = T { f1: 1, f2: 2 };
let T { f1: local1, f2: local2 } = &t;
// local1: &u64
// local2: &u64

And similarly with mutable references: 与可变引用类似:

let t = T { f1: 1, f2: 2 };
let T { f1: local1, f2: local2 } = &mut t;
// local1: &mut u64
// local2: &mut u64

This behavior can also work with nested structs. 此行为也适用于嵌套结构。

address 0x42 {
module example {
    struct X { f: u64 }
    struct Y { x1: X, x2: X }

    fun new_x(): X {
        X { f: 1 }
    }

    fun example() {
        let y = Y { x1: new_x(), x2: new_x() };

        let Y { x1: X { f }, x2 } = &y;
        assert!(*f + x2.f == 2, 42);

        let Y { x1: X { f: f1 }, x2: X { f: f2 } } = &mut y;
        *f1 = *f1 + 1;
        *f2 = *f2 + 1;
        assert!(*f1 + *f2 == 4, 42);
    }
}
}

Ignoring Values

In let bindings, it is often helpful to ignore some values. Local variables that start with _ will be ignored and not introduce a new variable

忽略值

在 let 绑定中,忽略某些值通常很有帮助。以 _ 开头的局部变量将被忽略,不会引入新变量

fun three(): (u64, u64, u64) {
    (0, 1, 2)
}
let (x1, _, z1) = three();
let (x2, _y, z2) = three();
assert!(x1 + z1 == x2 + z2)

This can be necessary at times as the compiler will error on unused local variables 这有时是必要的,因为编译器会在未使用的局部变量上出错

let (x1, y, z1) = three(); // ERROR!
//       ^ unused local 'y'

General let grammar

All of the different structures in let can be combined! With that we arrive at this general grammar for let statements:

一般 let 语法

let 中所有不同的结构都可以组合!这样,我们就得出了 let 语句的一般语法:

let-binding → let pattern-or-list type-annotationopt initializeropt > pattern-or-list → pattern | ( pattern-list ) > pattern-list → pattern ,opt | pattern , pattern-list > type-annotation → : type initializer → = expression

The general term for the item that introduces the bindings is a pattern. The pattern serves to both destructure data (possibly recursively) and introduce the bindings. The pattern grammar is as follows:

引入绑定的项目的通用术语是模式。该模式用于解构数据(可能是递归的)并引入绑定。模式语法如下:

pattern → local-variable | struct-type { field-binding-list } > field-binding-list → field-binding ,opt | field-binding , field-binding-list > field-binding → field | field : pattern

A few concrete examples with this grammar applied:

应用此语法的一些具体示例:

    let (x, y): (u64, u64) = (0, 1);
//       ^                           local-variable
//       ^                           pattern
//          ^                        local-variable
//          ^                        pattern
//          ^                        pattern-list
//       ^^^^                        pattern-list
//      ^^^^^^                       pattern-or-list
//            ^^^^^^^^^^^^           type-annotation
//                         ^^^^^^^^  initializer
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ let-binding

    let Foo { f, g: x } = Foo { f: 0, g: 1 };
//      ^^^                                    struct-type
//            ^                                field
//            ^                                field-binding
//               ^                             field
//                  ^                          local-variable
//                  ^                          pattern
//               ^^^^                          field-binding
//            ^^^^^^^                          field-binding-list
//      ^^^^^^^^^^^^^^^                        pattern
//      ^^^^^^^^^^^^^^^                        pattern-or-list
//                      ^^^^^^^^^^^^^^^^^^^^   initializer
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ let-binding

Mutations

Assignments

After the local is introduced (either by let or as a function parameter), the local can be modified via an assignment:

突变

作业

在引入局部后(通过 let 或作为函数参数),可以通过赋值来修改局部:

x = e

Unlike let bindings, assignments are expressions. In some languages, assignments return the value that was assigned, but in Move, the type of any assignment is always ().

与 let 绑定不同,赋值是表达式。在某些语言中,赋值返回被赋值的值,但在 Move 中,任何赋值的类型始终是 ()。

(x = e: ())

Practically, assignments being expressions means that they can be used without adding a new expression block with braces ({...}). 实际上,赋值是表达式意味着它们可以在不添加带有大括号 ({...}) 的新表达式块的情况下使用。

let x = 0;
if (cond) x = 1 else x = 2;

The assignment uses the same pattern syntax scheme as let bindings:

赋值使用与 let 绑定相同的模式语法方案:

address 0x42 {
module example {
    struct X { f: u64 }

    fun new_x(): X {
        X { f: 1 }
    }

    // This example will complain about unused variables and assignments.
    fun example() {
       let (x, _, z) = (0, 1, 3);
       let (x, y, f, g);

       (X { f }, X { f: x }) = (new_x(), new_x());
       assert!(f + x == 2, 42);

       (x, y, z, f, _, g) = (0, 0, 0, 0, 0, 0);
    }
}
}

Note that a local variable can only have one type, so the type of the local cannot change between assignments. 注意一个局部变量只能有一种类型,所以局部变量的类型不能在赋值之间改变。

let x;
x = 0;
x = false; // ERROR!

Mutating through a reference

In addition to directly modifying a local with assignment, a local can be modified via a mutable reference &mut.

通过引用进行变异

除了通过赋值直接修改局部外,还可以通过可变引用 &mut 修改局部。

let x = 0;
let r = &mut x;
*r = 1;
assert!(x == 1, 42)
}

This is particularly useful if either:

(1) You want to modify different variables depending on some condition.

这在以下情况下特别有用:

(1) 您想根据某些条件修改不同的变量。

let x = 0;
let y = 1;
let r = if (cond) &mut x else &mut y;
*r = *r + 1;

(2) You want another function to modify your local value.

(2) 你想要另一个函数来修改你的本地值。

let x = 0;
modify_ref(&mut x);

This sort of modification is how you modify structs and vectors!

这种修改就是你修改结构和向量的方式!

let v = vector::empty();
vector::push_back(&mut v, 100);
assert!(*vector::borrow(&v, 0) == 100, 42)

For more details, see Move references.

有关更多详细信息,请参阅移动引用。

Scopes

Any local declared with let is available for any subsequent expression, within that scope. Scopes are declared with expression blocks, {...}.

Locals cannot be used outside of the declared scope.

范围

使用 let 声明的任何本地表达式都可用于该范围内的任何后续表达式。范围用表达式块声明,{...}。

局部变量不能在声明的范围之外使用。

let x = 0;
{
    let y = 1;
};
x + y // ERROR!
//  ^ unbound local 'y'

But, locals from an outer scope can be used in a nested scope.

但是,来自外部作用域的本地变量可以在嵌套作用域中使用。

{
    let x = 0;
    {
        let y = x + 1; // valid
    }
}

Locals can be mutated in any scope where they are accessible. That mutation survives with the local, regardless of the scope that performed the mutation.

局部变量可以在可以访问的任何范围内进行变异。无论执行突变的范围如何,该突变都会在本地生存。

let x = 0;
x = x + 1;
assert!(x == 1, 42);
{
    x = x + 1;
    assert!(x == 2, 42);
};
assert!(x == 2, 42);

Expression Blocks

An expression block is a series of statements separated by semicolons (;). The resulting value of an expression block is the value of the last expression in the block.

表达式块

表达式块是由分号 (;) 分隔的一系列语句。表达式块的结果值是块中最后一个表达式的值。

{ let x = 1; let y = 1; x + y }

In this example, the result of the block is x + y.

A statement can be either a let declaration or an expression. Remember that assignments (x = e) are expressions of type ().

在此示例中,块的结果是 x + y。

语句可以是 let 声明或表达式。请记住,赋值 (x = e) 是 () 类型的表达式。

{ let x; let y = 1; x = 1; x + y }

Function calls are another common expression of type (). Function calls that modify data are commonly used as statements.

函数调用是类型 () 的另一种常见表达方式。修改数据的函数调用通常用作语句。

{ let v = vector::empty(); vector::push_back(&mut v, 1); v }

This is not just limited to () types---any expression can be used as a statement in a sequence!

这不仅限于 () 类型——任何表达式都可以用作序列中的语句!

{
    let x = 0;
    x + 1; // value is discarded
    x + 2; // value is discarded
    b"hello"; // value is discarded
}

But! If the expression contains a resource (a value without the drop ability), you will get an error. This is because Move's type system guarantees that any value that is dropped has the drop ability. (Ownership must be transferred or the value must be explicitly destroyed within its declaring module.)

但!如果表达式包含资源(没有丢弃能力的值),您将收到错误消息。这是因为 Move 的类型系统保证任何被删除的值都具有删除能力。 (必须转移所有权,或者必须在其声明模块中显式销毁该值。)

{
    let x = 0;
    Coin { value: x }; // ERROR!
//  ^^^^^^^^^^^^^^^^^ unused value without the `drop` ability
    x
}

If a final expression is not present in a block---that is, if there is a trailing semicolon ;, there is an implicit unit () value. Similarly, if the expression block is empty, there is an implicit unit () value.

如果块中不存在最终表达式——也就是说,如果有一个尾随分号;,则有一个隐含的 unit () 值。同样,如果表达式块为空,则存在隐含的 unit() 值。

// Both are equivalent
// 两者是等价的
{ x = x + 1; 1 / x; }
{ x = x + 1; 1 / x; () }
// Both are equivalent
{ }
{ () }

An expression block is itself an expression and can be used anyplace an expression is used. (Note: The body of a function is also an expression block, but the function body cannot be replaced by another expression.) 表达式块本身就是一个表达式,可以在任何使用表达式的地方使用。 (注意:函数体也是一个表达式块,但函数体不能被另一个表达式代替。)

let my_vector: vector<vector<u8>> = {
    let v = vector::empty();
    vector::push_back(&mut v, b"hello");
    vector::push_back(&mut v, b"goodbye");
    v
};

(The type annotation is not needed in this example and only added for clarity.) (此示例中不需要类型注释,只是为了清楚起见而添加。)

Shadowing

If a let introduces a local variable with a name already in scope, that previous variable can no longer be accessed for the rest of this scope. This is called shadowing.

隐藏

如果一个 let 引入了一个名称已经在作用域中的局部变量,则该作用域的其余部分将无法再访问先前的变量。这称为隐藏。

let x = 0;
assert!(x == 0, 42);

let x = 1; // x is shadowed
assert!(x == 1, 42);

When a local is shadowed, it does not need to retain the same type as before.

当局部被遮蔽时,它不需要保留与以前相同的类型。

let x = 0;
assert!(x == 0, 42);

let x = b"hello"; // x is shadowed
assert!(x == b"hello", 42);

After a local is shadowed, the value stored in the local still exists, but will no longer be accessible. This is important to keep in mind with values of types without the drop ability, as ownership of the value must be transferred by the end of the function.

在本地被遮蔽后,存储在本地的值仍然存在,但将不再可访问。对于没有删除能力的类型的值,请记住这一点很重要,因为值的所有权必须在函数结束时转移。

address 0x42 {
    module example {
        struct Coin has store { value: u64 }

        fun unused_resource(): Coin {
            let x = Coin { value: 0 }; // ERROR!
//              ^ This local still contains a value without the `drop` ability
            x.value = 1;
            let x = Coin { value: 10 };
            x
//          ^ Invalid return
        }
    }
}

When a local is shadowed inside a scope, the shadowing only remains for that scope. The shadowing is gone once that scope ends. 当本地在范围内被遮蔽时,该遮蔽仅保留在该范围内。一旦该范围结束,阴影就消失了。

let x = 0;
{
    let x = 1;
    assert!(x == 1, 42);
};
assert!(x == 0, 42);

Remember, locals can change type when they are shadowed.

请记住,本地人在被遮蔽时可以更改类型。

let x = 0;
{
    let x = b"hello";
    assert!(x = b"hello", 42);
};
assert!(x == 0, 42);

Move and Copy

All local variables in Move can be used in two ways, either by move or copy. If one or the other is not specified, the Move compiler is able to infer whether a copy or a move should be used. This means that in all of the examples above, a move or a copy would be inserted by the compiler. A local variable cannot be used without the use of move or copy.

copy will likely feel the most familiar coming from other programming languages, as it creates a new copy of the value inside of the variable to use in that expression. With copy, the local variable can be used more than once.

移动和复制

Move 中的所有局部变量都可以通过两种方式使用,通过移动或复制。如果未指定其中之一,则 Move 编译器能够推断应该使用副本还是移动。这意味着在上述所有示例中,编译器将插入移动或复制。如果不使用移动或复制,就不能使用局部变量。

复制可能会让人感觉最熟悉来自其他编程语言,因为它会在变量内部创建一个新的值副本以在该表达式中使用。使用复制,可以多次使用局部变量。

let x = 0;
let y = copy x + 1;
let z = copy x + 2;

Any value with the copy ability can be copied in this way.

move takes the value out of the local variable without copying the data. After a move occurs, the local variable is unavailable.

任何具有复制能力的值都可以通过这种方式复制。

move 从局部变量中取出值而不复制数据。移动发生后,局部变量不可用。

let x = 1;
let y = move x + 1;
//      ------ Local was moved here
let z = move x + 2; // Error!
//      ^^^^^^ Invalid usage of local 'x'
y + z

Safety

Move's type system will prevent a value from being used after it is moved. This is the same safety check described in let declaration that prevents local variables from being used before it is assigned a value.

安全

Move 的类型系统会阻止一个值在移动后被使用。这与 let 声明中描述的安全检查相同,可防止在为其赋值之前使用局部变量。

Inference

As mentioned above, the Move compiler will infer a copy or move if one is not indicated. The algorithm for doing so is quite simple:

  • Any scalar value with the copy ability is given a copy.
  • Any reference (both mutable &mut and immutable &) is given a copy.
    • Except under special circumstances where it is made a move for predictable borrow checker errors.
  • Any other value is given a move.
    • This means that even though other values might be have the copy ability, it must be done explicitly by the programmer.
    • This is to prevent accidental copies of large data structures.

For example:

推理

如上所述,如果未指明,Move 编译器将推断出副本或移动。这样做的算法非常简单:

  • 任何具有复制能力的标量值都会被赋予一个副本。
  • 任何引用(可变的 &mut 和不可变的 &)都会给出一个副本。
    • 除非在特殊情况下会因可预测的借用检查器错误而采取行动。
  • 任何其他值都会被移动。
    • 这意味着即使其他值可能具有复制能力,也必须由程序员明确完成。
    • 这是为了防止意外复制大型数据结构。 例如:
let s = b"hello";
let foo = Foo { f: 0 };
let coin = Coin { value: 0 };

let s2 = s; // move
let foo2 = foo; // move
let coin2 = coin; // move

let x = 0;
let b = false;
let addr = @0x42;
let x_ref = &x;
let coin_ref = &mut coin2;

let x2 = x; // copy
let b2 = b; // copy
let addr2 = @0x42; // copy
let x_ref2 = x_ref; // copy
let coin_ref2 = coin_ref; // copy

Equality

Move supports two equality operations == and !=

平等

Move 支持两个相等操作 == 和 !=

Operations

操作符

SyntaxOperationDescription
==equalReturns true if the two operands have the same value, false otherwise
!=not equalReturns true if the two operands have different values, false otherwise

Typing

Both the equal (==) and not-equal (!=) operations only work if both operands are the same type

打字

相等 (==) 和不相等 (!=) 操作仅在两个操作数为相同类型时才有效

0 == 0; // `true`
1u128 == 2u128; // `false`
b"hello" != x"00"; // `true`

Equality and non-equality also work over user defined types!

相等和不相等也适用于用户定义的类型!

address 0x42 {
module example {
    struct S has copy, drop { f: u64, s: vector<u8> }

    fun always_true(): bool {
        let s = S { f: 0, s: b"" };
        // parens are not needed but added for clarity in this example
        (copy s) == s
    }

    fun always_false(): bool {
        let s = S { f: 0, s: b"" };
        // parens are not needed but added for clarity in this example
        (copy s) != s
    }
}
}

If the operands have different types, there is a type checking error

如果操作数具有不同的类型,则存在类型检查错误

1u8 == 1u128; // ERROR!
//     ^^^^^ expected an argument of type 'u8'
b"" != 0; // ERROR!
//     ^ expected an argument of type 'vector<u8>'

Typing with references

When comparing references, the type of the reference (immutable or mutable) does not matter. This means that you can compare an immutable & reference with a mutable one &mut of the same underlying type.

使用参考打字

比较引用时,引用的类型(不可变或可变)无关紧要。这意味着您可以将不可变的 & 引用与相同基础类型的可变 &mut 进行比较。

let i = &0;
let m = &mut 1;

i == m; // `false`
m == i; // `false`
m == m; // `true`
i == i; // `true`

The above is equivalent to applying an explicit freeze to each mutable reference where needed

以上相当于在需要时对每个可变引用应用显式冻结

let i = &0;
let m = &mut 1;

i == freeze(m); // `false`
freeze(m) == i; // `false`
m == m; // `true`
i == i; // `true`

But again, the underlying type must be the same type

但同样,基础类型必须是相同的类型

let i = &0;
let s = &b"";

i == s; // ERROR!
//   ^ expected an argument of type '&u64'

Restrictions

Both == and != consume the value when comparing them. As a result, the type system enforces that the type must have drop. Recall that without the drop ability, ownership must be transferred by the end of the function, and such values can only be explicitly destroyed within their declaring module. If these were used directly with either equality == or non-equality !=, the value would be destroyed which would break drop ability safety guarantees!

限制

== 和 != 在比较它们时都会消耗值。结果,类型系统强制该类型必须具有 drop。回想一下,如果没有 drop 能力,所有权必须在函数结束时转移,并且这些值只能在其声明模块中显式销毁。如果这些直接与相等 == 或不相等 != 一起使用,则该值将被破坏,这将破坏掉落能力的安全保证!

address 0x42 {
module example {
    struct Coin has store { value: u64 }
    fun invalid(c1: Coin, c2: Coin) {
        c1 == c2 // ERROR!
//      ^^    ^^ These resources would be destroyed!
    }
}
}

But, a programmer can always borrow the value first instead of directly comparing the value, and reference types have the drop ability. For example

但是,程序员总是可以先借值而不是直接比较值,并且引用类型具有删除能力。例如

address 0x42 {
module example {
    struct Coin as store { value: u64 }
    fun swap_if_equal(c1: Coin, c2: Coin): (Coin, Coin) {
        let are_equal = &c1 == &c2; // valid
        if (are_equal) (c2, c1) else (c1, c2)
    }
}
}

Avoid Extra Copies

While a programmer can compare any value whose type has drop, a programmer should often compare by reference to avoid expensive copies.

避免额外的副本

虽然程序员可以比较任何类型下降的值,但程序员应该经常通过引用进行比较以避免昂贵的副本。

let v1: vector<u8> = function_that_returns_vector();
let v2: vector<u8> = function_that_returns_vector();
assert!(copy v1 == copy v2, 42);
//     ^^^^       ^^^^
use_two_vectors(v1, v2);

let s1: Foo = function_that_returns_large_struct();
let s2: Foo = function_that_returns_large_struct();
assert!(copy s1 == copy s2, 42);
//     ^^^^       ^^^^
use_two_foos(s1, s2);

This code is perfectly acceptable (assuming Foo has drop), just not efficient. The highlighted copies can be removed and replaced with borrows

这段代码是完全可以接受的(假设 Foo 已经下降),只是效率不高。突出显示的副本可以删除并替换为借用

let v1: vector<u8> = function_that_returns_vector();
let v2: vector<u8> = function_that_returns_vector();
assert!(&v1 == &v2, 42);
//     ^      ^
use_two_vectors(v1, v2);

let s1: Foo = function_that_returns_large_struct();
let s2: Foo = function_that_returns_large_struct();
assert!(&s1 == &s2, 42);
//     ^      ^
use_two_foos(s1, s2);

The efficiency of the == itself remains the same, but the copys are removed and thus the program is more efficient.

== 本身的效率保持不变,但副本被删除,因此程序效率更高。

Abort and Assert

return and abort are two control flow constructs that end execution, one for the current function and one for the entire transaction.

More information on return can be found in the linked section

中止和断言

return 和 abort 是结束执行的两种控制流结构,一种用于当前函数,一种用于整个事务。

有关退货的更多信息,请参见链接部分

abort

abort is an expression that takes one argument: an abort code of type u64. For example:

中止

abort 是一个带有一个参数的表达式:u64 类型的中止代码。例如:

abort 42

The abort expression halts execution the current function and reverts all changes made to global state by the current transaction. There is no mechanism for "catching" or otherwise handling an abort.

Luckily, in Move transactions are all or nothing, meaning any changes to global storage are made all at once only if the transaction succeeds. Because of this transactional commitment of changes, after an abort there is no need to worry about backing out changes. While this approach is lacking in flexibility, it is incredibly simple and predictable.

Similar to return, abort is useful for exiting control flow when some condition cannot be met.

In this example, the function will pop two items off of the vector, but will abort early if the vector does not have two items

abort 表达式停止执行当前函数并恢复当前事务对全局状态所做的所有更改。没有“捕获”或以其他方式处理中止的机制。

幸运的是,在 Move 中,事务是全有或全无,这意味着只有在事务成功时才会对全局存储进行任何更改。由于更改的这种事务性承诺,在中止之后无需担心撤销更改。虽然这种方法缺乏灵活性,但它非常简单且可预测。

与 return 类似,abort 对于在某些条件无法满足时退出控制流很有用。

在此示例中,该函数将从向量中弹出两个项目,但如果向量没有两个项目,该函数将提前中止

use std::vector;
fun pop_twice<T>(v: &mut vector<T>): (T, T) {
    if (vector::length(v) < 2) abort 42;

    (vector::pop_back(v), vector::pop_back(v))
}

This is even more useful deep inside a control-flow construct. For example, this function checks that all numbers in the vector are less than the specified bound. And aborts otherwise

这在控制流结构的深处甚至更有用。例如,此函数检查向量中的所有数字是否小于指定的界限。否则中止

use std::vector;
fun check_vec(v: &vector<u64>, bound: u64) {
    let i = 0;
    let n = vector::length(v);
    while (i < n) {
        let cur = *vector::borrow(v, i);
        if (cur > bound) abort 42;
        i = i + 1;
    }
}

assert

assert is a builtin, macro-like operation provided by the Move compiler. It takes two arguments, a condition of type bool and a code of type u64

断言

assert 是 Move 编译器提供的内置的类似宏的操作。它有两个参数,一个 bool 类型的条件和一个 u64 类型的代码

assert!(condition: bool, code: u64)

Since the operation is a macro, it must be invoked with the !. This is to convey that the arguments to assert are call-by-expression. In other words, assert is not a normal function and does not exist at the bytecode level. It is replaced inside the compiler with

由于该操作是一个宏,因此必须使用 ! 调用它。这是为了传达断言的参数是按表达式调用的。换句话说,assert 不是一个普通的函数,在字节码级别是不存在的。它在编译器内部被替换为

if (condition) () else abort code

assert is more commonly used than just abort by itself. The abort examples above can be rewritten using assert

assert 比 abort 本身更常用。上面的中止示例可以使用 assert 重写

use std::vector;
fun pop_twice<T>(v: &mut vector<T>): (T, T) {
    assert!(vector::length(v) >= 2, 42); // Now uses 'assert'

    (vector::pop_back(v), vector::pop_back(v))
}

and

use std::vector;
fun check_vec(v: &vector<u64>, bound: u64) {
    let i = 0;
    let n = vector::length(v);
    while (i < n) {
        let cur = *vector::borrow(v, i);
        assert!(cur <= bound, 42); // Now uses 'assert'
        i = i + 1;
    }
}

Note that because the operation is replaced with this if-else, the argument for the code is not always evaluated. For example:

请注意,由于该操作被替换为 if-else,因此并不总是评估代码的参数。例如:

assert!(true, 1 / 0)

Will not result in an arithmetic error, it is equivalent to

不会导致算术错误,相当于

if (true) () else (1 / 0)

So the arithmetic expression is never evaluated!

所以算术表达式永远不会被评估!

Abort codes in the Move VM

When using abort, it is important to understand how the u64 code will be used by the VM.

Normally, after successful execution, the Move VM produces a change-set for the changes made to global storage (added/removed resources, updates to existing resources, etc).

If an abort is reached, the VM will instead indicate an error. Included in that error will be two pieces of information:

  • The module that produced the abort (address and name)
  • The abort code.

For example

Move VM 中的中止代码

使用 abort 时,了解 VM 将如何使用 u64 代码非常重要。

通常,在成功执行后,Move VM 会为对全局存储所做的更改(添加/删除资源、更新现有资源等)生成一个更改集。

如果达到中止,VM 将改为指示错误。该错误中包含两条信息:

产生中止的模块(地址和名称) 中止代码。 例如

address 0x2 {
module example {
    public fun aborts() {
        abort 42
    }
}
}

script {
    fun always_aborts() {
        0x2::example::aborts()
    }
}

If a transaction, such as the script always_aborts above, calls 0x2::example::aborts, the VM would produce an error that indicated the module 0x2::example and the code 42.

This can be useful for having multiple aborts being grouped together inside a module.

In this example, the module has two separate error codes used in multiple functions

如果事务(例如上面的脚本 always_aborts)调用 0x2::example::aborts,VM 将产生一个错误,指示模块 0x2::example 和代码 42。

这对于在一个模块内将多个中止组合在一起很有用。

在此示例中,模块有两个单独的错误代码,用于多个功能

address 0x42 {
module example {

    use std::vector;

    const EMPTY_VECTOR: u64 = 0;
    const INDEX_OUT_OF_BOUNDS: u64 = 1;

    // move i to j, move j to k, move k to i
    public fun rotate_three<T>(v: &mut vector<T>, i: u64, j: u64, k: u64) {
        let n = vector::length(v);
        assert!(n > 0, EMPTY_VECTOR);
        assert!(i < n, INDEX_OUT_OF_BOUNDS);
        assert!(j < n, INDEX_OUT_OF_BOUNDS);
        assert!(k < n, INDEX_OUT_OF_BOUNDS);

        vector::swap(v, i, k);
        vector::swap(v, j, k);
    }

    public fun remove_twice<T>(v: &mut vector<T>, i: u64, j: u64): (T, T) {
        let n = vector::length(v);
        assert!(n > 0, EMPTY_VECTOR);
        assert!(i < n, INDEX_OUT_OF_BOUNDS);
        assert!(j < n, INDEX_OUT_OF_BOUNDS);
        assert!(i > j, INDEX_OUT_OF_BOUNDS);

        (vector::remove<T>(v, i), vector::remove<T>(v, j))
    }
}
}

The type of abort

The abort i expression can have any type! This is because both constructs break from the normal control flow, so they never need to evaluate to the value of that type.

The following are not useful, but they will type check

中止类型

abort i 表达式可以有任何类型!这是因为这两种构造都脱离了正常的控制流,因此它们永远不需要评估该类型的值。

以下没有用,但它们会键入检查

let y: address = abort 0;

This behavior can be helpful in situations where you have a branching instruction that produces a value on some branches, but not all. For example:

在您有一个分支指令在某些分支上产生值的情况下,这种行为可能会有所帮助,但不是全部。例如:

let b =
    if (x == 0) false
    else if (x == 1) true
    else abort 42;
//       ^^^^^^^^ `abort 42` has type `bool`

Conditionals

An if expression specifies that some code should only be evaluated if a certain condition is true. For example:

条件句

if 表达式指定仅当某个条件为真时才应评估某些代码。例如:

if (x > 5) x = x - 5

The condition must be an expression of type bool.

An if expression can optionally include an else clause to specify another expression to evaluate when the condition is false.

条件必须是布尔类型的表达式。

if 表达式可以选择包含 else 子句,以指定另一个表达式在条件为假时进行评估。

if (y <= 10) y = y + 1 else y = 10

Either the "true" branch or the "false" branch will be evaluated, but not both. Either branch can be a single expression or an expression block.

The conditional expressions may produce values so that the if expression has a result. 将评估“真”分支或“假”分支,但不会同时评估两者。任何一个分支都可以是单个表达式或表达式块。

条件表达式可以产生值,以便 if 表达式有结果。

let z = if (x < 100) x else 100;

The expressions in the true and false branches must have compatible types. For example:

true 和 false 分支中的表达式必须具有兼容的类型。例如:

// x and y must be u64 integers
let maximum: u64 = if (x > y) x else y;

// ERROR! branches different types
let z = if (maximum < 10) 10u8 else 100u64;

// ERROR! branches different types, as default false-branch is () not u64
if (maximum >= 10) maximum;

If the else clause is not specified, the false branch defaults to the unit value. The following are equivalent:

如果没有指定 else 子句,则 false 分支默认为单位值。以下是等价的:

if (condition) true_branch // implied default: else ()
if (condition) true_branch else ()

Commonly, if expressions are used in conjunction with expression blocks.

通常,if 表达式与表达式块一起使用。

let maximum = if (x > y) x else y;
if (maximum < 10) {
    x = x + 10;
    y = y + 10;
} else if (x >= 10 && y >= 10) {
    x = x - 10;
    y = y - 10;
}

Grammar for Conditionals

if-expression → if ( expression ) expression else-clauseopt else-clause → else expression

条件语法

if 表达式 → if ( 表达式 ) 表达式 else-clauseopt else-clause → else 表达式

While and Loop

Move offers two constructs for looping: while and loop.

While 和循环

Move 提供了两种循环结构:while 和 loop。

while loops

The while construct repeats the body (an expression of type unit) until the condition (an expression of type bool) evaluates to false.

Here is an example of simple while loop that computes the sum of the numbers from 1 to n:

while 循环

while 构造重复主体(单元类型的表达式),直到条件(布尔类型的表达式)评估为假。

下面是一个简单的 while 循环示例,它计算从 1 到 n 的数字之和:

fun sum(n: u64): u64 {
    let sum = 0;
    let i = 1;
    while (i <= n) {
        sum = sum + i;
        i = i + 1
    };

    sum
}

Infinite loops are allowed: 允许无限循环:

fun foo() {
    while (true) { }
}

break

The break expression can be used to exit a loop before the condition evaluates to false. For example, this loop uses break to find the smallest factor of n that's greater than 1:

break

break 表达式可用于在条件计算为假之前退出循环。例如,此循环使用 break 来查找 n 中大于 1 的最小因子:

fun smallest_factor(n: u64): u64 {
    // assuming the input is not 0 or 1
    let i = 2;
    while (i <= n) {
        if (n % i == 0) break;
        i = i + 1
    };

    i
}

The break expression cannot be used outside of a loop.

break 表达式不能在循环外使用。

continue

The continue expression skips the rest of the loop and continues to the next iteration. This loop uses continue to compute the sum of 1, 2, ..., n, except when the number is divisible by 10:

continue

continue 表达式跳过循环的其余部分并继续下一次迭代。此循环使用 continue 来计算 1、2、...、n 的总和,除非该数字能被 10 整除:

fun sum_intermediate(n: u64): u64 {
    let sum = 0;
    let i = 0;
    while (i < n) {
        i = i + 1;
        if (i % 10 == 0) continue;
        sum = sum + i;
    };

    sum
}

The continue expression cannot be used outside of a loop. continue 表达式不能在循环外使用。

The type of break and continue

break and continue, much like return and abort, can have any type. The following examples illustrate where this flexible typing can be helpful:

中断和继续的类型

break 和 continue 就像 return 和 abort 一样,可以有任何类型。以下示例说明了这种灵活的类型在哪些方面会有所帮助:

fun pop_smallest_while_not_equal(
    v1: vector<u64>,
    v2: vector<u64>,
): vector<u64> {
    let result = vector::empty();
    while (!vector::is_empty(&v1) && !vector::is_empty(&v2)) {
        let u1 = *vector::borrow(&v1, vector::length(&v1) - 1);
        let u2 = *vector::borrow(&v2, vector::length(&v2) - 1);
        let popped =
            if (u1 < u2) vector::pop_back(&mut v1)
            else if (u2 < u1) vector::pop_back(&mut v2)
            else break; // Here, `break` has type `u64`
        vector::push_back(&mut result, popped);
    };

    result
}
fun pick(
    indexes: vector<u64>,
    v1: &vector<address>,
    v2: &vector<address>
): vector<address> {
    let len1 = vector::length(v1);
    let len2 = vector::length(v2);
    let result = vector::empty();
    while (!vector::is_empty(&indexes)) {
        let index = vector::pop_back(&mut indexes);
        let chosen_vector =
            if (index < len1) v1
            else if (index < len2) v2
            else continue; // Here, `continue` has type `&vector<address>`
        vector::push_back(&mut result, *vector::borrow(chosen_vector, index))
    };

    result
}

The loop expression

The loop expression repeats the loop body (an expression with type ()) until it hits a break

Without a break, the loop will continue forever

循环表达式

循环表达式重复循环体(类型为 () 的表达式),直到遇到中断

没有中断,循环将永远继续

fun foo() {
    let i = 0;
    loop { i = i + 1 }
}

Here is an example that uses loop to write the sum function:

这是一个使用循环编写求和函数的示例:

fun sum(n: u64): u64 {
    let sum = 0;
    let i = 0;
    loop {
        i = i + 1;
        if (i > n) break;
        sum = sum + i
    };

    sum
}

As you might expect, continue can also be used inside a loop. Here is sum_intermediate from above rewritten using loop instead of while

如您所料, continue 也可以在循环内使用。这是上面使用循环而不是 while 重写的 sum_intermediate

fun sum_intermediate(n: u64): u64 {
    let sum = 0;
    let i = 0;
    loop {
        i = i + 1;
        if (i % 10 == 0) continue;
        if (i > n) break;
        sum = sum + i
    };

    sum
}

The type of while and loop

Move loops are typed expressions. A while expression always has type ().

while 和循环的类型

移动循环是类型化的表达式。 while 表达式始终具有 () 类型。

let () = while (i < 10) { i = i + 1 };

If a loop contains a break, the expression has type unit ()

如果循环包含中断,则表达式的类型为 unit ()

(loop { if (i < 10) i = i + 1 else break }: ());
let () = loop { if (i < 10) i = i + 1 else break };

If loop does not have a break, loop can have any type much like return, abort, break, and continue.

如果循环包含中断,则表达式的类型为 unit ()

(loop (): u64);
(loop (): address);
(loop (): &vector<vector<u8>>);

Functions

Function syntax in Move is shared between module functions and script functions. Functions inside of modules are reusable, whereas script functions are only used once to invoke a transaction.

函数

Move 中的函数语法在模块函数和脚本函数之间共享。模块内部的函数是可重用的,而脚本函数仅用于调用事务一次。

Declaration

Functions are declared with the fun keyword followed by the function name, type parameters, parameters, a return type, acquires annotations, and finally the function body.

声明

函数用 fun 关键字声明,后跟函数名、类型参数、形参、返回类型、获取注解,最后是函数体。

fun <identifier><[type_parameters: constraint],*>([identifier: type],*): <return_type> <acquires [identifier],*> <function_body>

For example

例如

fun foo<T1, T2>(x: u64, y: T1, z: T2): (T2, T1, u64) { (z, y, x) }

Visibility

Module functions, by default, can only be called within the same module. These internal (sometimes called private) functions cannot be called from other modules or from scripts.

可见性

默认情况下,模块函数只能在同一个模块内调用。这些内部(有时称为私有)函数不能从其他模块或脚本调用。

address 0x42 {
module m {
    fun foo(): u64 { 0 }
    fun calls_foo(): u64 { foo() } // valid
}

module other {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
    }
}
}

script {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
    }
}

To allow access from other modules or from scripts, the function must be declared public or public(friend). 要允许从其他模块或脚本访问,该函数必须声明为 public 或 public(friend)。

public visibility

A public function can be called by any function defined in any module or script. As shown in the following example, a public function can be called by:

  • other functions defined in the same module,
  • functions defined in another module, or
  • the function defined in a script.

public 可见性

公共函数可以被任何模块或脚本中定义的任何函数调用。如以下示例所示,可以通过以下方式调用公共函数:

在同一模块中定义的其他功能, 在另一个模块中定义的函数,或 脚本中定义的函数。

address 0x42 {
module m {
    public fun foo(): u64 { 0 }
    fun calls_foo(): u64 { foo() } // valid
}

module other {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // valid
    }
}
}

script {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // valid
    }
}

public(friend) visibility

The public(friend) visibility modifier is a more restricted form of the public modifier to give more control about where a function can be used. A public(friend) function can be called by:

  • other functions defined in the same module, or
  • functions defined in modules which are explicitly specified in the friend list (see Friends on how to specify the friend list).

Note that since we cannot declare a script to be a friend of a module, the functions defined in scripts can never call a public(friend) function.

public(friend) 可见性

public(friend) 可见性修饰符是 public 修饰符的一种更受限制的形式,可以更好地控制函数的使用位置。可以通过以下方式调用公共(朋友)函数:

在同一模块中定义的其他功能,或 在好友列表中明确指定的模块中定义的函数(请参阅好友了解如何指定好友列表)。 请注意,由于我们不能将脚本声明为模块的朋友,因此脚本中定义的函数永远不能调用 public(friend) 函数。

address 0x42 {
module m {
    friend 0x42::n;  // friend declaration
    public(friend) fun foo(): u64 { 0 }
    fun calls_foo(): u64 { foo() } // valid
}

module n {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // valid
    }
}

module other {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' can only be called from a 'friend' of module '0x42::m'
    }
}
}

script {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' can only be called from a 'friend' of module '0x42::m'
    }
}

entry modifier

The entry modifier is designed to allow module functions to be safely and directly invoked much like scripts. This allows module writers to specify which functions can be to begin execution. The module writer then knows that any non-entry function will be called from a Move program already in execution.

Essentially, entry functions are the "main" functions of a module, and they specify where Move programs start executing.

Note though, an entry function can still be called by other Move functions. So while they can serve as the start of a Move program, they aren't restricted to that case.

For example:

entry 修饰符

entry 修饰符旨在允许像脚本一样安全直接地调用模块函数。这允许模块编写者指定哪些函数可以开始执行。然后,模块编写者知道任何非入口函数都将从已经在执行的 Move 程序中调用。

本质上,入口函数是模块的“主要”函数,它们指定 Move 程序开始执行的位置。

但请注意,其他 Move 函数仍然可以调用入口函数。因此,虽然它们可以作为 Move 程序的开始,但它们并不局限于这种情况。

例如:

address 0x42 {
module m {
    public entry fun foo(): u64 { 0 }
    fun calls_foo(): u64 { foo() } // valid!
}

module n {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // valid!
    }
}

module other {
    public entry fun calls_m_foo(): u64 {
        0x42::m::foo() // valid!
    }
}
}

script {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // valid!
    }
}

Even internal functions can be marked as entry! This lets you guarantee that the function is called only at the beginning of execution (assuming you do not call it elsewhere in your module) 甚至内部函数也可以标记为入口!这使您可以保证仅在执行开始时调用该函数(假设您没有在模块的其他地方调用它)

address 0x42 {
module m {
    entry fun foo(): u64 { 0 } // valid! entry functions do not have to be public
}

module n {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
    }
}

module other {
    public entry fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
    }
}
}

script {
    fun calls_m_foo(): u64 {
        0x42::m::foo() // ERROR!
//      ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
    }
}

Name

Function names can start with letters a to z or letters A to Z. After the first character, function names can contain underscores _, letters a to z, letters A to Z, or digits 0 to 9.

名称

函数名称可以以字母 a 到 z 或字母 A 到 Z 开头。在第一个字符之后,函数名称可以包含下划线 _、字母 a 到 z、字母 A 到 Z 或数字 0 到 9。

fun FOO() {}
fun bar_42() {}
fun _bAZ19() {}

Type Parameters

After the name, functions can have type parameters

类型参数

在名称之后,函数可以有类型参数

fun id<T>(x: T): T { x }
fun example<T1: copy, T2>(x: T1, y: T2): (T1, T1, T2) { (copy x, x, y) }

For more details, see Move generics.

有关更多详细信息,请参阅移动泛型。

Parameters

Functions parameters are declared with a local variable name followed by a type annotation

参数

函数参数使用局部变量名声明,后跟类型注释

fun add(x: u64, y: u64): u64 { x + y }

We read this as x has type u64

A function does not have to have any parameters at all.

我们将其读为 x 具有 u64 类型

函数根本不需要任何参数。

fun useless() { }

This is very common for functions that create new or empty data structures

这对于创建新数据结构或空数据结构的函数很常见

address 0x42 {
module example {
  struct Counter { count: u64 }

  fun new_counter(): Counter {
      Counter { count: 0 }
  }

}
}

Acquires

When a function accesses a resource using move_from, borrow_global, or borrow_global_mut, the function must indicate that it acquires that resource. This is then used by Move's type system to ensure the references into global storage are safe, specifically that there are no dangling references into global storage.

收购

当函数使用 move_from、borrow_global 或 borrow_global_mut 访问资源时,该函数必须表明它获取了该资源。然后 Move 的类型系统使用它来确保对全局存储的引用是安全的,特别是没有对全局存储的悬空引用。

address 0x42 {
module example {

    struct Balance has key { value: u64 }

    public fun add_balance(s: &signer, value: u64) {
        move_to(s, Balance { value })
    }

    public fun extract_balance(addr: address): u64 acquires Balance {
        let Balance { value } = move_from(addr); // acquires needed
        value
    }
}
}

acquires annotations must also be added for transitive calls within the module. Calls to these functions from another module do not need to annotated with these acquires because one module cannot access resources declared in another module--so the annotation is not needed to ensure reference safety.

还必须为模块内的传递调用添加获取注释。从另一个模块对这些函数的调用不需要使用这些获取进行注释,因为一个模块无法访问在另一个模块中声明的资源——因此不需要注释来确保引用安全。

address 0x42 {
module example {

    struct Balance has key { value: u64 }

    public fun add_balance(s: &signer, value: u64) {
        move_to(s, Balance { value })
    }

    public fun extract_balance(addr: address): u64 acquires Balance {
        let Balance { value } = move_from(addr); // acquires needed
        value
    }

    public fun extract_and_add(sender: address, receiver: &signer) acquires Balance {
        let value = extract_balance(sender); // acquires needed here
        add_balance(receiver, value)
    }
}
}

address 0x42 {
module other {
    fun extract_balance(addr: address): u64 {
        0x42::example::extract_balance(addr) // no acquires needed
    }
}
}

A function can acquire as many resources as it needs to

一个函数可以根据需要获取尽可能多的资源

address 0x42 {
module example {
    use std::vector;

    struct Balance has key { value: u64 }
    struct Box<T> has key { items: vector<T> }

    public fun store_two<Item1: store, Item2: store>(
        addr: address,
        item1: Item1,
        item2: Item2,
    ) acquires Balance, Box {
        let balance = borrow_global_mut<Balance>(addr); // acquires needed
        balance.value = balance.value - 2;
        let box1 = borrow_global_mut<Box<Item1>>(addr); // acquires needed
        vector::push_back(&mut box1.items, item1);
        let box2 = borrow_global_mut<Box<Item2>>(addr); // acquires needed
        vector::push_back(&mut box2.items, item2);
    }
}
}

Return type

After the parameters, a function specifies its return type.

返回类型

在参数之后,函数指定其返回类型。

fun zero(): u64 { 0 }

Here : u64 indicates that the function's return type is u64.

Using tuples, a function can return multiple values

这里:u64 表示函数的返回类型是u64。

使用元组,一个函数可以返回多个值

fun one_two_three(): (u64, u64, u64) { (0, 1, 2) }

If no return type is specified, the function has an implicit return type of unit (). These functions are equivalent

如果未指定返回类型,则该函数具有隐式返回类型 unit ()。这些功能是等价的

fun just_unit(): () { () }
fun just_unit() { () }
fun just_unit() { }

script functions must have a return type of unit ()

脚本函数的返回类型必须为 unit ()

script {
    fun do_nothing() {
    }
}

As mentioned in the tuples section, these tuple "values" are virtual and do not exist at runtime. So for a function that returns unit (), it will not be returning any value at all during execution.

如元组部分所述,这些元组“值”是虚拟的,在运行时不存在。因此,对于返回 unit () 的函数,它在执行期间根本不会返回任何值。

Function body

A function's body is an expression block. The return value of the function is the last value in the sequence

函数体

函数体是一个表达式块。函数的返回值是序列中的最后一个值

fun example(): u64 {
    let x = 0;
    x = x + 1;
    x // returns 'x'
}

See the section below for more information on returns

For more information on expression blocks, see Move variables.

有关退货的更多信息,请参阅以下部分

有关表达式块的更多信息,请参阅移动变量。

Native Functions

Some functions do not have a body specified, and instead have the body provided by the VM. These functions are marked native.

Without modifying the VM source code, a programmer cannot add new native functions. Furthermore, it is the intent that native functions are used for either standard library code or for functionality needed for the given Move environment.

Most native functions you will likely see are in standard library code such as vector

原生函数

有些函数没有指定主体,而是由 VM 提供的主体。这些函数被标记为原生。

如果不修改 VM 源代码,程序员就无法添加新的本地函数。此外,本机函数的意图是用于标准库代码或给定 Move 环境所需的功能。

您可能会看到的大多数本机函数都在标准库代码中,例如向量

module std::vector {
    native public fun empty<Element>(): vector<Element>;
    ...
}

Calling

When calling a function, the name can be specified either through an alias or fully qualified

调用

调用函数时,名称可以通过别名或完全限定指定

address 0x42 {
module example {
    public fun zero(): u64 { 0 }
}
}

script {
    use 0x42::example::{Self, zero};
    fun call_zero() {
        // With the `use` above all of these calls are equivalent
        0x42::example::zero();
        example::zero();
        zero();
    }
}

When calling a function, an argument must be given for every parameter.

调用函数时,必须为每个参数指定一个参数。

address 0x42 {
module example {
    public fun takes_none(): u64 { 0 }
    public fun takes_one(x: u64): u64 { x }
    public fun takes_two(x: u64, y: u64): u64 { x + y }
    public fun takes_three(x: u64, y: u64, z: u64): u64 { x + y + z }
}
}

script {
    use 0x42::example;
    fun call_all() {
        example::takes_none();
        example::takes_one(0);
        example::takes_two(0, 1);
        example::takes_three(0, 1, 2);
    }
}

Type arguments can be either specified or inferred. Both calls are equivalent.

可以指定或推断类型参数。两个调用是等价的。

address 0x42 {
module example {
    public fun id<T>(x: T): T { x }
}
}

script {
    use 0x42::example;
    fun call_all() {
        example::id(0);
        example::id<u64>(0);
    }
}

For more details, see Move generics.

有关更多详细信息,请参阅移动泛型。

Returning values

The result of a function, its "return value", is the final value of its function body. For example

返回值

一个函数的结果,它的“返回值”,是它的函数体的最终值。例如

fun add(x: u64, y: u64): u64 {
    x + y
}

As mentioned above, the function's body is an expression block. The expression block can sequence various statements, and the final expression in the block will be be the value of that block

如上所述,函数体是一个表达式块。表达式块可以对各种语句进行排序,块中的最终表达式将是该块的值

fun double_and_add(x: u64, y: u64): u64 {
    let double_x = x * 2;
    let double_y = y * 2;
    double_x + double_y
}

The return value here is double_x + double_y

这里的返回值为 double_x + double_y

return expression

A function implicitly returns the value that its body evaluates to. However, functions can also use the explicit return expression:

返回表达式

函数隐式返回其主体计算的值。但是,函数也可以使用显式返回表达式:

fun f1(): u64 { return 0 }
fun f2(): u64 { 0 }

These two functions are equivalent. In this slightly more involved example, the function subtracts two u64 values, but returns early with 0 if the second value is too large:

这两个功能是等价的。在这个稍微复杂的示例中,该函数减去两个 u64 值,但如果第二个值太大,则提前返回 0:

fun safe_sub(x: u64, y: u64): u64 {
    if (y > x) return 0;
    x - y
}

Note that the body of this function could also have been written as if (y > x) 0 else x - y.

However return really shines is in exiting deep within other control flow constructs. In this example, the function iterates through a vector to find the index of a given value:

请注意,这个函数的主体也可以写成 if (y x) 0 else x - y。

然而 return 真正闪耀的是在其他控制流结构的深处退出。在此示例中,函数遍历向量以查找给定值的索引:

use std::vector;
use std::option::{Self, Option};
fun index_of<T>(v: &vector<T>, target: &T): Option<u64> {
    let i = 0;
    let n = vector::length(v);
    while (i < n) {
        if (vector::borrow(v, i) == target) return option::some(i);
        i = i + 1
    };

    option::none()
}

Using return without an argument is shorthand for return (). That is, the following two functions are equivalent:

使用不带参数的 return 是 return () 的简写。即以下两个函数是等价的:

fun foo() { return }
fun foo() { return () }

Structs and Resources

A struct is a user-defined data structure containing typed fields. Structs can store any non-reference type, including other structs.

We often refer to struct values as resources if they cannot be copied and cannot be dropped. In this case, resource values must have ownership transferred by the end of the function. This property makes resources particularly well served for defining global storage schemas or for representing important values (such as a token).

By default, structs are linear and ephemeral. By this we mean that they: cannot be copied, cannot be dropped, and cannot be stored in global storage. This means that all values have to have ownership transferred (linear) and the values must be dealt with by the end of the program's execution (ephemeral). We can relax this behavior by giving the struct abilities which allow values to be copied or dropped and also to be stored in global storage or to define global storage schemas.

结构和资源

结构是包含类型字段的用户定义数据结构。结构可以存储任何非引用类型,包括其他结构。

如果结构值无法复制且无法删除,我们通常将其称为资源。在这种情况下,资源值必须在函数结束时转移所有权。此属性使资源特别适合用于定义全局存储模式或表示重要值(例如令牌)。

默认情况下,结构是线性的和短暂的。我们的意思是它们:不能被复制,不能被删除,不能被存储在全局存储中。这意味着所有值都必须转移所有权(线性),并且必须在程序执行结束时处理这些值(临时)。我们可以通过赋予 struct 允许复制或删除值以及存储在全局存储中或定义全局存储模式的能力来放松这种行为。

Defining Structs

Structs must be defined inside a module:

定义结构

结构必须在模块内定义:

address 0x2 {
module m {
    struct Foo { x: u64, y: bool }
    struct Bar {}
    struct Baz { foo: Foo, }
    //                   ^ note: it is fine to have a trailing comma
}
}

Structs cannot be recursive, so the following definition is invalid: 结构不能递归,所以下面的定义是无效的:

struct Foo { x: Foo }
//              ^ error! Foo cannot contain Foo

As mentioned above: by default, a struct declaration is linear and ephemeral. So to allow the value to be used with certain operations (that copy it, drop it, store it in global storage, or use it as a storage schema), structs can be granted abilities by annotating them with has <ability>:

如上所述:默认情况下,结构声明是线性且短暂的。因此,为了允许将值用于某些操作(复制、删除、将其存储在全局存储中或将其用作存储模式),可以通过使用 has ability 注释它们来授予结构能力:

address 0x2 {
module m {
    struct Foo has copy, drop { x: u64, y: bool }
}
}

For more details, see the annotating structs section. 有关更多详细信息,请参阅注释结构部分。

Naming

Structs must start with a capital letter A to Z. After the first letter, constant names can contain underscores _, letters a to z, letters A to Z, or digits 0 to 9.

命名

结构必须以大写字母 A 到 Z 开头。在第一个字母之后,常量名称可以包含下划线 _、字母 a 到 z、字母 A 到 Z 或数字 0 到 9。

struct Foo {}
struct BAR {}
struct B_a_z_4_2 {}

This naming restriction of starting with A to Z is in place to give room for future language features. It may or may not be removed later.

这种以 A 到 Z 开头的命名限制是为了给未来的语言特性留出空间。以后可能会或可能不会删除它。

Using Structs

Creating Structs

Values of a struct type can be created (or "packed") by indicating the struct name, followed by value for each field:

使用结构

创建结构

可以通过指示结构名称来创建(或“打包”)结构类型的值,然后是每个字段的值:

address 0x2 {
module m {
    struct Foo has drop { x: u64, y: bool }
    struct Baz has drop { foo: Foo }

    fun example() {
        let foo = Foo { x: 0, y: false };
        let baz = Baz { foo: foo };
    }
}
}

If you initialize a struct field with a local variable whose name is the same as the field, you can use the following shorthand:

如果使用与字段名称相同的局部变量初始化结构字段,则可以使用以下简写:

let baz = Baz { foo: foo };
// is equivalent to
let baz = Baz { foo };

This is called sometimes called "field name punning".

这有时称为“字段名称双关语”。

Destroying Structs via Pattern Matching

Struct values can be destroyed by binding or assigning them patterns.

通过模式匹配销毁结构

结构值可以通过绑定或分配模式来销毁。

address 0x2 {
module m {
    struct Foo { x: u64, y: bool }
    struct Bar { foo: Foo }
    struct Baz {}

    fun example_destroy_foo() {
        let foo = Foo { x: 3, y: false };
        let Foo { x, y: foo_y } = foo;
        //        ^ shorthand for `x: x`

        // two new bindings
        //   x: u64 = 3
        //   foo_y: bool = false
    }

    fun example_destroy_foo_wildcard() {
        let foo = Foo { x: 3, y: false };
        let Foo { x, y: _ } = foo;
        // only one new binding since y was bound to a wildcard
        //   x: u64 = 3
    }

    fun example_destroy_foo_assignment() {
        let x: u64;
        let y: bool;
        Foo { x, y } = Foo { x: 3, y: false };
        // mutating existing variables x & y
        //   x = 3, y = false
    }

    fun example_foo_ref() {
        let foo = Foo { x: 3, y: false };
        let Foo { x, y } = &foo;
        // two new bindings
        //   x: &u64
        //   y: &bool
    }

    fun example_foo_ref_mut() {
        let foo = Foo { x: 3, y: false };
        let Foo { x, y } = &mut foo;
        // two new bindings
        //   x: &mut u64
        //   y: &mut bool
    }

    fun example_destroy_bar() {
        let bar = Bar { foo: Foo { x: 3, y: false } };
        let Bar { foo: Foo { x, y } } = bar;
        //             ^ nested pattern
        // two new bindings
        //   x: u64 = 3
        //   foo_y: bool = false
    }

    fun example_destroy_baz() {
        let baz = Baz {};
        let Baz {} = baz;
    }
}
}

Borrowing Structs and Fields

The & and &mut operator can be used to create references to structs or fields. These examples include some optional type annotations (e.g., : &Foo) to demonstrate the type of operations.

借用结构和字段

& 和 &mut 运算符可用于创建对结构或字段的引用。这些示例包括一些可选的类型注释(例如:&Foo)来演示操作的类型。

let foo = Foo { x: 3, y: true };
let foo_ref: &Foo = &foo;
let y: bool = foo_ref.y;          // reading a field via a reference to the struct
let x_ref: &u64 = &foo.x;

let x_ref_mut: &mut u64 = &mut foo.x;
*x_ref_mut = 42;            // modifying a field via a mutable reference

It is possible to borrow inner fields of nested structs.

可以借用嵌套结构的内部字段。

let foo = Foo { x: 3, y: true };
let bar = Bar { foo };

let x_ref = &bar.foo.x;

You can also borrow a field via a reference to a struct.

您还可以通过对结构的引用来借用字段。

let foo = Foo { x: 3, y: true };
let foo_ref = &foo;
let x_ref = &foo_ref.x;
// this has the same effect as let x_ref = &foo.x

Reading and Writing Fields

If you need to read and copy a field's value, you can then dereference the borrowed field

阅读和写作领域

如果您需要读取和复制字段的值,则可以取消引用借用的字段

let foo = Foo { x: 3, y: true };
let bar = Bar { foo: copy foo };
let x: u64 = *&foo.x;
let y: bool = *&foo.y;
let foo2: Foo = *&bar.foo;

If the field is implicitly copyable, the dot operator can be used to read fields of a struct without any borrowing. (Only scalar values with the copy ability are implicitly copyable.)

如果该字段是隐式可复制的,则点运算符可用于读取结构的字段而无需任何借用。 (只有具有复制能力的标量值是隐式可复制的。)

let foo = Foo { x: 3, y: true };
let x = foo.x;  // x == 3
let y = foo.y;  // y == true

Dot operators can be chained to access nested fields.

点运算符可以链接起来访问嵌套字段。

let baz = Baz { foo: Foo { x: 3, y: true } };
let x = baz.foo.x; // x = 3;

However, this is not permitted for fields that contain non-primitive types, such a vector or another struct

但是,对于包含非原始类型(例如向量或其他结构)的字段,这是不允许的

let foo = Foo { x: 3, y: true };
let bar = Bar { foo };
let foo2: Foo = *&bar.foo;
let foo3: Foo = bar.foo; // error! add an explicit copy with *&

The reason behind this design decision is that copying a vector or another struct might be an expensive operation. It is important for a programmer to be aware of this copy and make others aware with the explicit syntax *&

In addition reading from fields, the dot syntax can be used to modify fields, regardless of the field being a primitive type or some other struct

这个设计决策背后的原因是复制一个向量或另一个结构可能是一项昂贵的操作。对于程序员来说,了解这个副本并使用显式语法 *& 让其他人了解是很重要的

除了从字段中读取之外,点语法还可用于修改字段,无论该字段是原始类型还是其他结构

let foo = Foo { x: 3, y: true };
foo.x = 42;     // foo = Foo { x: 42, y: true }
foo.y = !foo.y; // foo = Foo { x: 42, y: false }
let bar = Bar { foo };            // bar = Bar { foo: Foo { x: 42, y: false } }
bar.foo.x = 52;                   // bar = Bar { foo: Foo { x: 52, y: false } }
bar.foo = Foo { x: 62, y: true }; // bar = Bar { foo: Foo { x: 62, y: true } }

The dot syntax also works via a reference to a struct

点语法也可以通过对结构的引用来工作

let foo = Foo { x: 3, y: true };
let foo_ref = &mut foo;
foo_ref.x = foo_ref.x + 1;

Privileged Struct Operations

Most struct operations on a struct type T can only be performed inside the module that declares T:

  • Struct types can only be created ("packed"), destroyed ("unpacked") inside the module that defines the struct.
  • The fields of a struct are only accessible inside the module that defines the struct.

Following these rules, if you want to modify your struct outside the module, you will need to provide publis APIs for them. The end of the chapter contains some examples of this.

However, struct types are always visible to another module or script:

特权结构操作

大多数对结构类型 T 的结构操作只能在声明 T 的模块内执行:

  • 结构类型只能在定义结构的模块内创建(“打包”)、销毁(“解包”)。
  • 结构的字段只能在定义结构的模块内部访问。 遵循这些规则,如果你想在模块之外修改你的结构,你需要为它们提供 publis API。本章的最后包含了这方面的一些例子。

但是,结构类型始终对另一个模块或脚本可见:

// m.move
address 0x2 {
module m {
    struct Foo has drop { x: u64 }

    public fun new_foo(): Foo {
        Foo { x: 42 }
    }
}
}
// n.move
address 0x2 {
module n {
    use 0x2::m;

    struct Wrapper has drop {
        foo: m::Foo
    }

    fun f1(foo: m::Foo) {
        let x = foo.x;
        //      ^ error! cannot access fields of `foo` here
    }

    fun f2() {
        let foo_wrapper = Wrapper { foo: m::new_foo() };
    }
}
}

Note that structs do not have visibility modifiers (e.g., public or private).

请注意,结构没有可见性修饰符(例如,公共或私有)。

Ownership

As mentioned above in Defining Structs, structs are by default linear and ephemeral. This means they cannot be copied or dropped. This property can be very useful when modeling real world resources like money, as you do not want money to be duplicated or get lost in circulation.

所有权

正如上面定义结构中提到的,结构默认是线性的和短暂的。这意味着它们不能被复制或删除。在模拟货币等现实世界资源时,此属性非常有用,因为您不希望货币被复制或在流通中丢失。

address 0x2 {
module m {
    struct Foo { x: u64 }

    public fun copying_resource() {
        let foo = Foo { x: 100 };
        let foo_copy = copy foo; // error! 'copy'-ing requires the 'copy' ability
        let foo_ref = &foo;
        let another_copy = *foo_ref // error! dereference requires the 'copy' ability
    }

    public fun destroying_resource1() {
        let foo = Foo { x: 100 };

        // error! when the function returns, foo still contains a value.
        // This destruction requires the 'drop' ability
    }

    public fun destroying_resource2(f: &mut Foo) {
        *f = Foo { x: 100 } // error!
                            // destroying the old value via a write requires the 'drop' ability
    }
}
}

To fix the second example (fun dropping_resource), you would need to manually "unpack" the resource:

要修复第二个示例(有趣的 drop_resource),您需要手动“解包”资源:

address 0x2 {
module m {
    struct Foo { x: u64 }

    public fun destroying_resource1_fixed() {
        let foo = Foo { x: 100 };
        let Foo { x: _ } = foo;
    }
}
}

Recall that you are only able to deconstruct a resource within the module in which it is defined. This can be leveraged to enforce certain invariants in a system, for example, conservation of money.

If on the other hand, your struct does not represent something valuable, you can add the abilities copy and drop to get a struct value that might feel more familiar from other programming languages:

回想一下,您只能在定义资源的模块中解构资源。这可以用来在系统中强制执行某些不变量,例如货币守恒。

另一方面,如果您的结构不代表有价值的东西,您可以添加功能复制和删除以获取可能对其他编程语言更熟悉的结构值:

address 0x2 {
module m {
    struct Foo has copy, drop { x: u64 }

    public fun run() {
        let foo = Foo { x: 100 };
        let foo_copy = copy foo;
        // ^ this code copies foo, whereas `let x = foo` or
        // `let x = move foo` both move foo

        let x = foo.x;            // x = 100
        let x_copy = foo_copy.x;  // x = 100

        // both foo and foo_copy are implicitly discarded when the function returns
    }
}
}

Storing Resources in Global Storage

Only structs with the key ability can be saved directly in persistent global storage. All values stored within those key structs must have the store abilities. See the ability and global storage chapters for more detail.

在全局存储中存储资源

只有具有关键能力的结构才能直接保存在持久性全局存储中。存储在这些键结构中的所有值都必须具有存储能力。有关更多详细信息,请参阅能力和全局存储章节。

Examples

Here are two short examples of how you might use structs to represent valuable data (in the case of Coin) or more classical data (in the case of Point and Circle)

例子

这里有两个简短的示例,说明如何使用结构来表示有价值的数据(在 Coin 的情况下)或更经典的数据(在 Point 和 Circle 的情况下)

Example 1: Coin

示例 1:硬币

address 0x2 {
module m {
    // We do not want the Coin to be copied because that would be duplicating this "money",
    // so we do not give the struct the 'copy' ability.
    // Similarly, we do not want programmers to destroy coins, so we do not give the struct the
    // 'drop' ability.
    // However, we *want* users of the modules to be able to store this coin in persistent global
    // storage, so we grant the struct the 'store' ability. This struct will only be inside of
    // other resources inside of global storage, so we do not give the struct the 'key' ability.
    struct Coin has store {
        value: u64,
    }

    public fun mint(value: u64): Coin {
        // You would want to gate this function with some form of access control to prevent
        // anyone using this module from minting an infinite amount of coins
        Coin { value }
    }

    public fun withdraw(coin: &mut Coin, amount: u64): Coin {
        assert!(coin.balance >= amount, 1000);
        coin.value = coin.value - amount;
        Coin { value: amount }
    }

    public fun deposit(coin: &mut Coin, other: Coin) {
        let Coin { value } = other;
        coin.value = coin.value + value;
    }

    public fun split(coin: Coin, amount: u64): (Coin, Coin) {
        let other = withdraw(&mut coin, amount);
        (coin, other)
    }

    public fun merge(coin1: Coin, coin2: Coin): Coin {
        deposit(&mut coin1, coin2);
        coin1
    }

    public fun destroy_zero(coin: Coin) {
        let Coin { value } = coin;
        assert!(value == 0, 1001);
    }
}
}

Example 2: Geometry

示例 2:几何

address 0x2 {
module point {
    struct Point has copy, drop, store {
        x: u64,
        y: u64,
    }

    public fun new(x: u64, y: u64): Point {
        Point {
            x, y
        }
    }

    public fun x(p: &Point): u64 {
        p.x
    }

    public fun y(p: &Point): u64 {
        p.y
    }

    fun abs_sub(a: u64, b: u64): u64 {
        if (a < b) {
            b - a
        }
        else {
            a - b
        }
    }

    public fun dist_squared(p1: &Point, p2: &Point): u64 {
        let dx = abs_sub(p1.x, p2.x);
        let dy = abs_sub(p1.y, p2.y);
        dx*dx + dy*dy
    }
}
}
address 0x2 {
module circle {
    use 0x2::Point::{Self, Point};

    struct Circle has copy, drop, store {
        center: Point,
        radius: u64,
    }

    public fun new(center: Point, radius: u64): Circle {
        Circle { center, radius }
    }

    public fun overlaps(c1: &Circle, c2: &Circle): bool {
        let d = Point::dist_squared(&c1.center, &c2.center);
        let r1 = c1.radius;
        let r2 = c2.radius;
        d*d <= r1*r1 + 2*r1*r2 + r2*r2
    }
}
}

Constants

Constants are a way of giving a name to shared, static values inside of a module or script.

The constant's must be known at compilation. The constant's value is stored in the compiled module or script. And each time the constant is used, a new copy of that value is made.

常数

常量是为模块或脚本内的共享静态值命名的一种方式。

常量必须在编译时知道。常量的值存储在编译的模块或脚本中。每次使用该常量时,都会生成该值的新副本。

Declaration

Constant declarations begin with the const keyword, followed by a name, a type, and a value. They can exist in either a script or module

声明

常量声明以 const 关键字开头,后跟名称、类型和值。它们可以存在于脚本或模块中

const <name>: <type> = <expression>;

For example

例如

script {

    const MY_ERROR_CODE: u64 = 0;

    fun main(input: u64) {
        assert!(input > 0, MY_ERROR_CODE);
    }

}

address 0x42 {
module example {

    const MY_ADDRESS: address = @0x42;

    public fun permissioned(s: &signer) {
        assert!(std::signer::address_of(s) == MY_ADDRESS, 0);
    }

}
}

Naming

Constants must start with a capital letter A to Z. After the first letter, constant names can contain underscores _, letters a to z, letters A to Z, or digits 0 to 9.

命名

常量必须以大写字母 A 到 Z 开头。在第一个字母之后,常量名称可以包含下划线 _、字母 a 到 z、字母 A 到 Z 或数字 0 到 9。

const FLAG: bool = false;
const MY_ERROR_CODE: u64 = 0;
const ADDRESS_42: address = @0x42;

Even though you can use letters a to z in a constant. The general style guidelines are to use just uppercase letters A to Z, with underscores _ between each word.

This naming restriction of starting with A to Z is in place to give room for future language features. It may or may not be removed later.

即使您可以在常数中使用字母 a 到 z。一般的风格准则是只使用大写字母 A 到 Z,每个单词之间用下划线 _。

这种以 A 到 Z 开头的命名限制是为了给未来的语言特性留出空间。以后可能会或可能不会删除它。

Visibility

public constants are not currently supported. const values can be used only in the declaring module.

可见性

当前不支持公共常量。 const 值只能在声明模块中使用。

Valid Expressions

Currently, constants are limited to the primitive types bool, u8, u64, u128, address, and vector<u8>. Future support for other vector values (besides the "string"-style literals) will come later.

有效表达式

目前,常量仅限于基本类型 bool、u8、u64、u128、address 和向量 u8。未来对其他向量值的支持(除了“字符串”样式的文字)将在稍后提供。

Values

Commonly, consts are assigned a simple value, or literal, of their type. For example

值

通常,为 const 分配其类型的简单值或文字。例如

const MY_BOOL: bool = false;
const MY_ADDRESS: address = @0x70DD;
const BYTES: vector<u8> = b"hello world";
const HEX_BYTES: vector<u8> = x"DEADBEEF";

Complex Expressions

In addition to literals, constants can include more complex expressions, as long as the compiler is able to reduce the expression to a value at compile time.

Currently, equality operations, all boolean operations, all bitwise operations, and all arithmetic operations can be used.

复杂表达式

除了文字之外,常量还可以包含更复杂的表达式,只要编译器能够在编译时将表达式简化为一个值即可。

目前,可以使用相等运算、所有布尔运算、所有位运算和所有算术运算。

const RULE: bool = true && false;
const CAP: u64 = 10 * 100 + 1;
const SHIFTY: u8 = {
  (1 << 1) * (1 << 2) * (1 << 3) * (1 << 4)
};
const HALF_MAX: u128 = 340282366920938463463374607431768211455 / 2;
const EQUAL: bool = 1 == 1;

If the operation would result in a runtime exception, the compiler will give an error that it is unable to generate the constant's value

如果操作会导致运行时异常,编译器将给出无法生成常量值的错误

const DIV_BY_ZERO: u64 = 1 / 0; // error!
const SHIFT_BY_A_LOT: u64 = 1 << 100; // error!
const NEGATIVE_U64: u64 = 0 - 1; // error!

Note that constants cannot currently refer to other constants. This feature, along with support for other expressions, will be added in the future. 请注意,常量当前不能引用其他常量。将来会添加此功能以及对其他表达式的支持。

泛型

泛型可用于定义具有不同输入数据类型的函数和结构体。这种语言特性有时被称为参数多态(parametric polymorphism)。在 Move 中,我们经常将术语泛型与类型形参(type parameter)和类型实参(type argument)互换使用。(有些书籍的中文翻译通常将 type parameter 和 type argument 不加以区别地翻译为“类型参数”,译者注)

泛型通常用于库(library)代码中,例如向量中,声明适用于任何可能的实例化(满足指定约束)的代码。在其他框架中,泛型代码有时可用多种不同的方式与全局存储进行交互,这些方式有着相同的实现。

声明类型参数

函数和结构体都可以在其签名中带上类型参数列表,由一对尖括号括起来 <...>。

泛型函数

函数的类型参数放在函数名称之后和(值)参数列表之前。以下代码定义了一个泛型标识函数,该函数接受任何类型的值并返回原值。

fun id<T>(x: T): T {
    // 此类型标注是不必要但有效的
    (x: T)
}

一旦定义,类型参数 T 就可以在参数类型、返回类型和函数体内使用。

泛型结构体

结构体的类型参数放在结构名称之后,可用于命名字段的类型。

struct Foo<T> has copy, drop { x: T }

struct Bar<T1, T2> has copy, drop {
    x: T1,
    y: vector<T2>,
}

请注意,未使用的类型参数。

类型实参

调用泛型函数

调用泛型函数时,可以在由一对尖括号括起来的列表中为函数的类型形参指定类型实参。

fun foo() {
    let x = id<bool>(true);
}

如果你不指定类型实参,Move 的类型推断(功能)将为你提供它们。

使用泛型结构体

类似地,在构造或销毁泛型类型的值时,可以为结构体的类型参数附加一个类型实参列表。

fun foo() {
    let foo = Foo<bool> { x: true };
    let Foo<bool> { x } = foo;
}

如果你不指定类型实参,Move 的类型推断(功能)将为你提供它们。

类型实参不匹配

如果你指定类型实参并且它们与提供的实际值冲突,则会报错:

fun foo() {
    let x = id<u64>(true); // 错误!true 不是 u64
}

同样地:

fun foo() {
    let foo = Foo<bool> { x: 0 }; // 错误!0 不是布尔值
    let Foo<address> { x } = foo; // 错误!bool 与 address 不兼容
}

类型推断

在大多数情况下,Move 编译器能够推断类型实参,因此你不必显式地写下它们。如果我们省略类型实参,上面的例子会是这样的:

fun foo() {
    let x = id(true);
    //        ^ 被推断为 <bool>

    let foo = Foo { x: true };
    //           ^ 被推断为 <bool>

    let Foo { x } = foo;
    //     ^ 被推断为 <bool>
}

注意:当编译器无法推断类型时,你需要手动标注它们。一个常见的场景是调用一个函数,其类型参数只出现在返回位置。

address 0x2 {
module m {
    using std::vector;

    fun foo() {
        // let v = vector::new();
        //                    ^ 编译器无法确定元素类型。

        let v = vector::new<u64>();
        //                 ^~~~~ 必须手动标注。
    }
}
}

但是,如果稍后在该函数中使用该返回值,编译器将能够推断其类型:

address 0x2 {
module m {
    using std::vector;

    fun foo() {
        let v = vector::new();
        //                 ^ 被推断为 <u64>
        vector::push_back(&mut v, 42);
    }
}
}

未使用的类型参数

对于结构体定义,未使用的类型参数是没有出现在结构体定义的任何字段中,但在编译时静态检查的类型参数。Move 允许未使用的类型参数,因此以下结构体定义有效:

struct Foo<T> {
    foo: u64
}

这在对某些概念建模时会很方便。这是一个例子:

address 0x2 {
module m {
    // 货币说明符
    struct Currency1 {}
    struct Currency2 {}

    // 可以使用货币说明符类型实例化的泛型钱币类型。
    // 例如 Coin<Currency1>, Coin<Currency2> 等。
    struct Coin<Currency> has store {
        value: u64
    }

    // 泛型地编写有关所有货币的代码
    public fun mint_generic<Currency>(value: u64): Coin<Currency> {
        Coin { value }
    }

    // 具体编写关于一种货币的代码
    public fun mint_concrete(value: u64): Coin<Currency1> {
        Coin { value }
    }
}
}

在此示例中,struct Coin<Currency> 是类型参数为 Currency 的泛型结构体,该参数指定钱币的货币(类型),并允许将代码泛型地写入任何货币或具体地写入特定货币。即使 Currency 类型参数未出现在 Coin 中定义的任何字段中,这种通用性也适用。

虚类型参数

在上面的例子中,虽然 struct Coin 要求有 store 能力,但 Coin<Currency1> 和 Coin<Currency2> 都没有 store 能力。这实际是因为条件能力与泛型类型的规则以及 Currency1 和 Currency2 没有 store 能力,尽管它们甚至没有在 struct Coin 的结构体中使用。这可能会导致一些不合意的后果。例如,我们无法将 Coin<Currency1> 放入全局存储中的钱包。

一种可能的解决方案是向 Currency1 和 Currency2 添加伪能力(spurious ability)标注(例如:struct Currency1 has store {})。但是,这可能会导致错误(bug)或安全漏洞,因为它削弱了类型,引入了不必要的能力声明。例如,我们永远不会期望全局存储中的资源有一个类型为 Currency1 的字段,但是通过伪 store 能力这是有可能的。此外,伪标注具有传染性,需要在许多未使用类型参数的泛型函数上也包含必要的约束。

虚类型(phantom type)参数解决了这个问题。未使用的类型参数可以标记为 phantom 类型参数,不参与结构体的能力推导。这样,在派生泛型类型的能力时,不考虑虚类型参数的实参,从而避免了对伪能力标注的需要。为了使这个宽松的规则合理,Move 的类型系统保证声明为 phantom 的参数要么在结构体定义根本不使用,要么仅用作声明为 phantom 的类型参数的实参。

声明

在结构定义中,可以通过在声明前添加 phantom 关键字来将类型参数声明为 phantom。如果一个类型参数被声明为 phantom,我们就说它是一个虚类型参数。在定义结构时,Move 的类型检查器确保每个虚类型参数要么未在结构定义中使用,要么仅用作虚类型参数的实参。

更正式地说,如果一个类型被用作虚类型参数的实参,我们说该类型出现在_虚位置_。有了这个定义,正确使用虚参数的规则可以指定如下:虚类型参数只能出现在虚位置。

以下两个示例显示了虚参数的合法使用。在第一个中,结构定义中根本没有使用参数 T1。在第二个中,参数 T1 仅用作虚类型参数的实参。

struct S1<phantom T1, T2> { f: u64 }
                  ^^
                  Ok: T1 没有出现在结构定义中

struct S2<phantom T1, T2> { f: S1<T1, T2> }
                                  ^^
                                  Ok: T1 出现在虚位置

以下代码展示违反规则的示例:

struct S1<phantom T> { f: T }
                          ^
                          错误:不是虚位置

struct S2<T> { f: T }

struct S3<phantom T> { f: S2<T> }
                             ^
                             错误:不是虚位置

实例化

实例化结构时,在派生结构能力时排除虚参数的实参。例如,考虑以下代码:

struct S<T1, phantom T2> has copy { f: T1 }
struct NoCopy {}
struct HasCopy has copy {}

现在考虑类型 S<HasCopy, NoCopy>。因为 S 是用 copy 定义的,并且所有非虚参数都有 copy 能力,所以 S<HasCopy, NoCopy> 也有 copy 能力。

具有能力约束的虚类型参数

能力约束和虚类型参数是正交特征,虚参数可以用能力约束来声明。当实例化具有能力约束的虚类型参数时,类型实参必须满足该约束,即使该参数是虚的(phantom)。例如,以下定义是完全有效的:

struct S<phantom T: copy> {}

通常用来限制应用并且 T 只能用具有 copy 的实参实例化。

约束

在上面的示例中,我们演示了如何使用类型参数来定义稍后可以由调用者插入的“未知”类型。然而,这意味着类型系统几乎没有关于类型的信息,并且必须以非常保守的方式执行检查。在某种意义上,类型系统必须为不受约束的泛型假设最坏的情况。简单地说,默认泛型类型参数没有能力。

这就是约束发挥作用的地方:它们提供了一种方法来指定这些未知类型具有哪些属性,以便类型系统可以允许在其他情况下不安全的操作。

声明约束

可以使用以下语法对类型参数施加约束。

// T 是类型参数的名称
T: <ability> (+ <ability>)*

<ability> 可以是四种能力中的任何一种,一个类型参数可以同时被多种能力约束。因此,以下所有内容都是有效的类型参数声明:

T: copy
T: copy + drop
T: copy + drop + store + key

验证约束

在调用点检查约束,所以下面的代码不会编译。

struct Foo<T: key> { x: T }

struct Bar { x: Foo<u8> }
//                  ^ 错误!u8 没有 'key'

struct Baz<T> { x: Foo<T> }
//                     ^ 错误! t 没有 'key'
struct R {}

fun unsafe_consume<T>(x: T) {
    // 错误!x 没有 'drop'
}

fun consume<T: drop>(x: T) {
    // 合法!
    // x 会被自动删除
}

fun foo() {
    let r = R {};
    consume<R>(r);
    //      ^ 错误!r 没有 'drop'
}
struct R {}

fun unsafe_double<T>(x: T) {
    (copy x, x)
    // 错误!x 没有 'copy'
}

fun double<T: copy>(x: T) {
    (copy x, x) // 合法!
}

fun foo(): (R, R) {
    let r = R {};
    double<R>(r)
    //     ^ 错误!R 没有 'error'
}

有关详细信息,请参阅有关条件能力与泛型类型。

递归的限制

递归结构体

泛型结构不能直接或间接包含相同类型的字段,即使具有不同类型的参数也是如此。以下所有结构定义均无效:

struct Foo<T> {
    x: Foo<u64> // 错误!'Foo' 包含 'Foo'
}

struct Bar<T> {
    x: Bar<T> // 错误!'Bar' 包含 'Bar'
}

// 错误!'A' 和 'B' 形成一个循环,这也是不允许的。
struct A<T> {
    x: B<T, u64>
}

struct B<T1, T2> {
    x: A<T1>
    y: A<T2>
}

高级主题:类型级递归

Move 允许递归调用泛型函数。然而,当与泛型结构体结合使用时,在某些情况下这可能会创建无限数量的类型,这意味着会给编译器、虚拟机(mv)和其他语言组件增加不必要的复杂性。因此,这样的递归是被禁止的。

被允许的用法:

address 0x2 {
module m {
    struct A<T> {}

    // 有限多种类型 —— 允许。
    // foo<T> -> foo<T> -> foo<T> -> ... is valid
    fun foo<T>() {
        foo<T>();
    }

    // 有限多种类型 —— 允许。
    // foo<T> -> foo<A<u64>> -> foo<A<u64>> -> ... is valid
    fun foo<T>() {
        foo<A<u64>>();
    }
}
}

不被允许的用法:

address 0x2 {
module m {
    struct A<T> {}

    // 无限多种类型 —— 不允许。
    // 错误!
    // foo<T> -> foo<A<T>> -> foo<A<A<T>>> -> ...
    fun foo<T>() {
        foo<Foo<T>>();
    }
}
}
address 0x2 {
module n {
    struct A<T> {}

    // 无限多种类型 —— 不允许。
    // 错误!
    // foo<T1, T2> -> bar<T2, T1> -> foo<T2, A<T1>>
    //   -> bar<A<T1>, T2> -> foo<A<T1>, A<T2>>
    //   -> bar<A<T2>, A<T1>> -> foo<A<T2>, A<A<T1>>>
    //   -> ...
    fun foo<T1, T2>() {
        bar<T2, T1>();
    }

    fun bar<T1, T2> {
        foo<T1, A<T2>>();
    }
}
}

请注意,类型级递归的检查基于对调用点的保守分析,所以不考虑控制流或运行时值。

address 0x2 {
module m {
    struct A<T> {}

    fun foo<T>(n: u64) {
        if (n > 0) {
            foo<A<T>>(n - 1);
        };
    }
}
}

上面示例中的函数在技术上将终止任何给定的输入,因此只会创建有限多种类型,但它仍然被 Move 的类型系统视为无效的。

Abilities

Abilities are a typing feature in Move that control what actions are permissible for values of a given type. This system grants fine grained control over the "linear" typing behavior of values, as well as if and how values are used in global storage. This is implemented by gating access to certain bytecode instructions so that for a value to be used with the bytecode instruction, it must have the ability required (if one is required at all—not every instruction is gated by an ability).

能力

能力是 Move 中的一种输入功能,用于控制对给定类型的值允许哪些操作。该系统对值的“线性”类型行为以及值是否以及如何在全局存储中使用提供细粒度控制。这是通过对某些字节码指令的访问进行门控来实现的,因此对于要与字节码指令一起使用的值,它必须具有所需的能力(如果完全需要——不是每条指令都由能力门控)。

The Four Abilities

The four abilities are:

四种能力

四种能力分别是:

  • copy
    • Allows values of types with this ability to be copied.
    • 允许复制具有此能力的类型的值。
  • drop
    • Allows values of types with this ability to be popped/dropped.
    • 允许弹出/删除具有此能力的类型的值。
  • store
    • Allows values of types with this ability to exist inside a struct in global storage.
    • 允许具有这种能力的类型的值存在于全局存储的结构中。
  • key
    • Allows the type to serve as a key for global storage operations.
    • 允许该类型作为全局存储操作的键。

copy

The copy ability allows values of types with that ability to be copied. It gates the ability to copy values out of local variables with the copy operator and to copy values via references with dereference *e.

If a value has copy, all values contained inside of that value have copy.

复制能力允许复制具有该能力的类型的值。它控制了使用复制运算符从局部变量中复制值以及通过取消引用 *e 的引用复制值的能力。

如果一个值有副本,则该值内包含的所有值都有副本。

drop

The drop ability allows values of types with that ability to be dropped. By dropped, we mean that value is not transferred and is effectively destroyed as the Move program executes. As such, this ability gates the ability to ignore values in a multitude of locations, including:

If a value has drop, all values contained inside of that value have drop.

丢弃能力允许丢弃具有该能力的类型的值。被丢弃,我们的意思是价值没有被转移,并且在 Move 程序执行时被有效地销毁。因此,此能力限制了在多个位置忽略值的能力,包括:

  • 不使用局部变量或参数中的值
  • 不使用序列中的值;
  • 覆盖赋值变量中的值
  • 写入 *e1 = e2 时通过引用覆盖值。

如果一个值下降,则该值内包含的所有值都下降。

store

The store ability allows values of types with this ability to exist inside of a struct (resource) in global storage, but not necessarily as a top-level resource in global storage. This is the only ability that does not directly gate an operation. Instead it gates the existence in global storage when used in tandem with key.

If a value has store, all values contained inside of that value have store

存储能力允许具有这种能力的类型的值存在于全局存储中的结构(资源)内部,但不一定作为全局存储中的顶级资源。这是唯一不直接控制操作的能力。相反,当与 key 一起使用时,它会限制全局存储中的存在。

如果一个值具有存储,则该值内包含的所有值都具有存储

key

The key ability allows the type to serve as a key for global storage operations. It gates all global storage operations, so in order for a type to be used with move_to, borrow_global, move_from, etc., the type must have the key ability. Note that the operations still must be used in the module where the key type is defined (in a sense, the operations are private to the defining module).

If a value has key, all values contained inside of that value have store. This is the only ability with this sort of asymmetry.

密钥能力允许该类型作为全局存储操作的密钥。它对所有全局存储操作进行门控,因此要使类型与 move_to、borrow_global、move_from 等一起使用,该类型必须具有 key 能力。请注意,这些操作仍然必须在定义密钥类型的模块中使用(从某种意义上说,这些操作是定义模块的私有)。

如果一个值有键,则包含在该值内的所有值都有存储。这是唯一具有这种不对称性的能力。

Builtin Types

Most primitive, builtin types have copy, drop, and store with the exception of signer, which just has store

  • bool, u8, u64, u128, and address all have copy, drop, and store.
  • signer has drop
    • Cannot be copied and cannot be put into global storage
  • vector<T> may have copy, drop, and store depending on the abilities of T.
  • Immutable references & and mutable references &mut both have copy and drop.
    • This refers to copying and dropping the reference itself, not what they refer to.
    • References cannot appear in global storage, hence they do not have store.

None of the primitive types have key, meaning none of them can be used directly with the global storage operations.

内置类型

大多数原始的内置类型都有复制、删除和存储,但签名者除外,它只有存储

  • bool, u8, u64, u128, 和address都有copy、drop和store。
  • 签名者有下降
    • 无法复制,无法放入全局存储
  • 根据 T 的能力,向量 T 可能具有复制、删除和存储。
    • 有关更多详细信息,请参阅条件能力和通用类型。
  • 不可变引用 & 和可变引用 &mut 都有复制和删除。
    • 这是指复制和删除引用本身,而不是它们所指的内容。
    • 引用不能出现在全局存储中,因此它们没有存储。 所有原始类型都没有键,这意味着它们都不能直接用于全局存储操作。

Annotating Structs

To declare that a struct has an ability, it is declared with has <ability> after the struct name but before the fields. For example:

注释结构

要声明结构具有能力,请在结构名称之后但在字段之前使用具有能力来声明它。例如:

struct Ignorable has drop { f: u64 }
struct Pair has copy, drop, store { x: u64, y: u64 }

In this case: Ignorable has the drop ability. Pair has copy, drop, and store.

All of these abilities have strong guarantees over these gated operations. The operation can be performed on the value only if it has that ability; even if the value is deeply nested inside of some other collection!

As such: when declaring a struct’s abilities, certain requirements are placed on the fields. All fields must satisfy these constraints. These rules are necessary so that structs satisfy the reachability rules for the abilities given above. If a struct is declared with the ability...

  • copy, all fields must have copy.
  • drop, all fields must have drop.
  • store, all fields must have store.
  • key, all fields must have store.
    • key is the only ability currently that doesn’t require itself.

For example: 在这种情况下: Ignorable 具有丢弃能力。 Pair 具有复制、删除和存储功能。

所有这些能力对这些门控操作都有强有力的保证。只有具有该能力,才能对值执行操作;即使该值深深嵌套在其他集合中!

因此:在声明结构的能力时,对字段提出了某些要求。所有字段都必须满足这些约束。这些规则是必要的,以便结构满足上述功能的可达性规则。如果一个结构被声明为具有能力......

  • copy,所有字段都必须有副本。
  • drop,所有字段都必须有drop。
  • store,所有字段都必须有store。
  • key,所有字段都必须有存储。
    • key是目前唯一不需要自己的能力。 例如:
// A struct without any abilities
struct NoAbilities {}

struct WantsCopy has copy {
    f: NoAbilities, // ERROR 'NoAbilities' does not have 'copy'
}

and similarly: 同样:

// A struct without any abilities
struct NoAbilities {}

struct MyResource has key {
    f: NoAbilities, // Error 'NoAbilities' does not have 'store'
}

Conditional Abilities and Generic Types

When abilities are annotated on a generic type, not all instances of that type are guaranteed to have that ability. Consider this struct declaration:

条件能力和通用类型

在泛型类型上注释能力时,并非该类型的所有实例都保证具有该能力。考虑这个结构声明:

struct Cup<T> has copy, drop, store, key { item: T }

It might be very helpful if Cup could hold any type, regardless of its abilities. The type system can see the type parameter, so it should be able to remove abilities from Cup if it sees a type parameter that would violate the guarantees for that ability.

This behavior might sound a bit confusing at first, but it might be more understandable if we think about collection types. We could consider the builtin type vector to have the following type declaration: 如果 Cup 可以容纳任何类型,无论其能力如何,这可能会非常有帮助。类型系统可以看到类型参数,因此如果它看到一个类型参数会违反该能力的保证,它应该能够从 Cup 中删除能力。

这种行为一开始可能听起来有点令人困惑,但如果我们考虑一下集合类型,它可能会更容易理解。我们可以考虑内置类型向量具有以下类型声明:

vector<T> has copy, drop, store;

We want vectors to work with any type. We don't want separate vector types for different abilities. So what are the rules we would want? Precisely the same that we would want with the field rules above. So, it would be safe to copy a vector value only if the inner elements can be copied. It would be safe to ignore a vector value only if the inner elements can be ignored/dropped. And, it would be safe to put a vector in global storage only if the inner elements can be in global storage.

To have this extra expressiveness, a type might not have all the abilities it was declared with depending on the instantiation of that type; instead, the abilities a type will have depends on both its declaration and its type arguments. For any type, type parameters are pessimistically assumed to be used inside of the struct, so the abilities are only granted if the type parameters meet the requirements described above for fields. Taking Cup from above as an example:

  • Cup has the ability copy only if T has copy.
  • It has drop only if T has drop.
  • It has store only if T has store.
  • It has key only if T has store.

Here are examples for this conditional system for each ability:

我们希望向量适用于任何类型。我们不希望针对不同的能力使用不同的向量类型。那么我们想要的规则是什么?与上面的字段规则完全相同。因此,仅当可以复制内部元素时,复制向量值才是安全的。仅当可以忽略/删除内部元素时,忽略向量值才是安全的。而且,仅当内部元素可以在全局存储中时,将向量放入全局存储中才是安全的。

为了拥有这种额外的表现力,一个类型可能不具备它声明的所有能力,具体取决于该类型的实例化;相反,一个类型的能力取决于它的声明和它的类型参数。对于任何类型,类型参数都被悲观地假定为在结构内部使用,因此只有在类型参数满足上述字段要求时才授予能力。以上面的 Cup 为例:

  • 只有 T 有副本,Cup 才有能力副本。
  • 只有当 T 有下降时它才有下降。
  • 只有当 T 有存储时它才有存储。
  • 只有当 T 有存储时它才有密钥。

以下是每个能力的条件系统的示例:

Example: conditional copy

struct NoAbilities {}
struct S has copy, drop { f: bool }
struct Cup<T> has copy, drop, store { item: T }

fun example(c_x: Cup<u64>, c_s: Cup<S>) {
    // Valid, 'Cup<u64>' has 'copy' because 'u64' has 'copy'
    let c_x2 = copy c_x;
    // Valid, 'Cup<S>' has 'copy' because 'S' has 'copy'
    let c_s2 = copy c_s;
}

fun invalid(c_account: Cup<signer>, c_n: Cup<NoAbilities>) {
    // Invalid, 'Cup<signer>' does not have 'copy'.
    // Even though 'Cup' was declared with copy, the instance does not have 'copy'
    // because 'signer' does not have 'copy'
    let c_account2 = copy c_account;
    // Invalid, 'Cup<NoAbilities>' does not have 'copy'
    // because 'NoAbilities' does not have 'copy'
    let c_n2 = copy c_n;
}

Example: conditional drop

struct NoAbilities {}
struct S has copy, drop { f: bool }
struct Cup<T> has copy, drop, store { item: T }

fun unused() {
    Cup<bool> { item: true }; // Valid, 'Cup<bool>' has 'drop'
    Cup<S> { item: S { f: false }}; // Valid, 'Cup<S>' has 'drop'
}

fun left_in_local(c_account: Cup<signer>): u64 {
    let c_b = Cup<bool> { item: true };
    let c_s = Cup<S> { item: S { f: false }};
    // Valid return: 'c_account', 'c_b', and 'c_s' have values
    // but 'Cup<signer>', 'Cup<bool>', and 'Cup<S>' have 'drop'
    0
}

fun invalid_unused() {
    // Invalid, Cannot ignore 'Cup<NoAbilities>' because it does not have 'drop'.
    // Even though 'Cup' was declared with 'drop', the instance does not have 'drop'
    // because 'NoAbilities' does not have 'drop'
    Cup<NoAbilities> { item: NoAbilities {}};
}

fun invalid_left_in_local(): u64 {
    let n = Cup<NoAbilities> { item: NoAbilities {}};
    // Invalid return: 'c_n' has a value
    // and 'Cup<NoAbilities>' does not have 'drop'
    0
}

Example: conditional store

struct Cup<T> has copy, drop, store { item: T }

// 'MyInnerResource' is declared with 'store' so all fields need 'store'
struct MyInnerResource has store {
    yes: Cup<u64>, // Valid, 'Cup<u64>' has 'store'
    // no: Cup<signer>, Invalid, 'Cup<signer>' does not have 'store'
}

// 'MyResource' is declared with 'key' so all fields need 'store'
struct MyResource has key {
    yes: Cup<u64>, // Valid, 'Cup<u64>' has 'store'
    inner: Cup<MyInnerResource>, // Valid, 'Cup<MyInnerResource>' has 'store'
    // no: Cup<signer>, Invalid, 'Cup<signer>' does not have 'store'
}

Example: conditional key

struct NoAbilities {}
struct MyResource<T> has key { f: T }

fun valid(account: &signer) acquires MyResource {
    let addr = signer::address_of(account);
     // Valid, 'MyResource<u64>' has 'key'
    let has_resource = exists<MyResource<u64>>(addr);
    if (!has_resource) {
         // Valid, 'MyResource<u64>' has 'key'
        move_to(account, MyResource<u64> { f: 0 })
    };
    // Valid, 'MyResource<u64>' has 'key'
    let r = borrow_global_mut<MyResource<u64>>(addr)
    r.f = r.f + 1;
}

fun invalid(account: &signer) {
   // Invalid, 'MyResource<NoAbilities>' does not have 'key'
   let has_it = exists<MyResource<NoAbilities>>(addr);
   // Invalid, 'MyResource<NoAbilities>' does not have 'key'
   let NoAbilities {} = move_from<NoAbilities>(addr);
   // Invalid, 'MyResource<NoAbilities>' does not have 'key'
   move_to(account, NoAbilities {});
   // Invalid, 'MyResource<NoAbilities>' does not have 'key'
   borrow_global<NoAbilities>(addr);
}

Uses and Aliases

The use syntax can be used to create aliases to members in other modules. use can be used to create aliases that last either for the entire module, or for a given expression block scope.

用途和别名

use 语法可用于为其他模块中的成员创建别名。 use 可用于为整个模块或给定的表达式块范围创建别名。

Syntax

There are several different syntax cases for use. Starting with the most simple, we have the following for creating aliases to other modules

句法

有几种不同的语法案例可供使用。从最简单的开始,我们有以下用于为其他模块创建别名

use <address>::<module name>;
use <address>::<module name> as <module alias name>;

For example

例如

use std::vector;
use std::vector as V;

use std::vector; introduces an alias vector for std::vector. This means that anywhere you would want to use the module name std::vector (assuming this use is in scope), you could use vector instead. use std::vector; is equivalent to use std::vector as vector;

Similarly use std::vector as V; would let you use V instead of std::vector

使用标准::向量;为 std::vector 引入别名向量。这意味着在任何您想使用模块名称 std::vector 的地方(假设此使用在范围内),您都可以使用 vector 代替。使用标准::向量;相当于使用 std::vector 作为向量;

同样使用 std::vector 作为 V;会让你使用 V 而不是 std::vector

use std::vector;
use std::vector as V;

fun new_vecs(): (vector<u8>, vector<u8>, vector<u8>) {
    let v1 = std::vector::empty();
    let v2 = vector::empty();
    let v3 = V::empty();
    (v1, v2, v3)
}

If you want to import a specific module member (such as a function, struct, or constant). You can use the following syntax.

如果要导入特定的模块成员(例如函数、结构或常量)。您可以使用以下语法。

use <address>::<module name>::<module member>;
use <address>::<module name>::<module member> as <member alias>;

For example

例如

use std::vector::empty;
use std::vector::empty as empty_vec;

This would let you use the function std::vector::empty without full qualification. Instead you could use empty and empty_vec respectively. Again, use std::vector::empty; is equivalent to use std::vector::empty as empty;

这将允许您在没有完全限定的情况下使用函数 std::vector::empty。相反,您可以分别使用 empty 和 empty_vec。再次,使用 std::vector::empty;相当于使用 std::vector::empty 作为空;

use std::vector::empty;
use std::vector::empty as empty_vec;

fun new_vecs(): (vector<u8>, vector<u8>, vector<u8>) {
    let v1 = std::vector::empty();
    let v2 = empty();
    let v3 = empty_vec();
    (v1, v2, v3)
}

If you want to add aliases for multiple module members at once, you can do so with the following syntax

如果要一次为多个模块成员添加别名,可以使用以下语法

use <address>::<module name>::{<module member>, <module member> as <member alias> ... };

For example

例如

use std::vector::{push_back, length as len, pop_back};

fun swap_last_two<T>(v: &mut vector<T>) {
    assert!(len(v) >= 2, 42);
    let last = pop_back(v);
    let second_to_last = pop_back(v);
    push_back(v, last);
    push_back(v, second_to_last)
}

If you need to add an alias to the Module itself in addition to module members, you can do that in a single use using Self. Self is a member of sorts that refers to the module.

如果除了模块成员之外,您还需要为模块本身添加别名,您可以使用 Self 一次性完成。 Self 是指模块的各种成员。

use std::vector::{Self, empty};

For clarity, all of the following are equivalent:

为清楚起见,以下所有内容都是等效的:

use std::vector;
use std::vector as vector;
use std::vector::Self;
use std::vector::Self as vector;
use std::vector::{Self};
use std::vector::{Self as vector};

If needed, you can have as many aliases for any item as you like

如果需要,您可以为任何项目设置任意数量的别名

use std::vector::{
    Self,
    Self as V,
    length,
    length as len,
};

fun pop_twice<T>(v: &mut vector<T>): (T, T) {
    // all options available given the `use` above
    assert!(vector::length(v) > 1, 42);
    assert!(V::length(v) > 1, 42);
    assert!(length(v) > 1, 42);
    assert!(len(v) > 1, 42);

    (vector::pop_back(v), vector::pop_back(v))
}

Inside a module

Inside of a module all use declarations are usable regardless of the order of declaration.

模块内部

在模块内部,无论声明顺序如何,所有 use 声明都是可用的。

address 0x42 {
module example {
    use std::vector;

    fun example(): vector<u8> {
        let v = empty();
        vector::push_back(&mut v, 0);
        vector::push_back(&mut v, 10);
        v
    }

    use std::vector::empty;
}
}

The aliases declared by use in the module usable within that module.

Additionally, the aliases introduced cannot conflict with other module members. See Uniqueness for more details

在该模块中可用的模块中使用声明的别名。

此外,引入的别名不能与其他模块成员冲突。有关详细信息,请参阅唯一性

Inside an expression

You can add use declarations to the beginning of any expression block

在表达式内部

您可以将 use 声明添加到任何表达式块的开头

address 0x42 {
module example {

    fun example(): vector<u8> {
        use std::vector::{empty, push_back};

        let v = empty();
        push_back(&mut v, 0);
        push_back(&mut v, 10);
        v
    }
}
}

As with let, the aliases introduced by use in an expression block are removed at the end of that block.

与 let 一样,在表达式块中使用 use 引入的别名在该块的末尾被删除。

address 0x42 {
module example {

    fun example(): vector<u8> {
        let result = {
            use std::vector::{empty, push_back};
            let v = empty();
            push_back(&mut v, 0);
            push_back(&mut v, 10);
            v
        };
        result
    }

}
}

Attempting to use the alias after the block ends will result in an error

在块结束后尝试使用别名将导致错误

fun example(): vector<u8> {
    let result = {
        use std::vector::{empty, push_back};
        let v = empty();
        push_back(&mut v, 0);
        push_back(&mut v, 10);
        v
    };
    let v2 = empty(); // ERROR!
//           ^^^^^ unbound function 'empty'
    result
}

Any use must be the first item in the block. If the use comes after any expression or let, it will result in a parsing error

任何使用都必须是块中的第一项。如果 use 出现在任何表达式或 let 之后,则会导致解析错误

{
    let x = 0;
    use std::vector; // ERROR!
    let v = vector::empty();
}

Naming rules

Aliases must follow the same rules as other module members. This means that aliases to structs or constants must start with A to Z

命名规则

别名必须遵循与其他模块成员相同的规则。这意味着结构或常量的别名必须以 A 到 Z 开头

address 0x42 {
module data {
    struct S {}
    const FLAG: bool = false;
    fun foo() {}
}
module example {
    use 0x42::data::{
        S as s, // ERROR!
        FLAG as fLAG, // ERROR!
        foo as FOO,  // valid
        foo as bar, // valid
    };
}
}

Uniqueness

Inside a given scope, all aliases introduced by use declarations must be unique.

For a module, this means aliases introduced by use cannot overla

独特性

在给定范围内,所有由 use 声明引入的别名必须是唯一的。

对于一个模块,这意味着使用引入的别名不能重叠

address 0x42 {
module example {

    use std::vector::{empty as foo, length as foo}; // ERROR!
    //                                        ^^^ duplicate 'foo'

    use std::vector::empty as bar;

    use std::vector::length as bar; // ERROR!
    //                         ^^^ duplicate 'bar'

}
}

And, they cannot overlap with any of the module's other members

而且,它们不能与模块的任何其他成员重叠

address 0x42 {
module data {
    struct S {}
}
module example {
    use 0x42::data::S;

    struct S { value: u64 } // ERROR!
    //     ^ conflicts with alias 'S' above
}
}

Inside of an expression block, they cannot overlap with each other, but they can shadow other aliases or names from an outer scope

在表达式块内部,它们不能相互重叠,但它们可以遮蔽外部作用域中的其他别名或名称

Shadowing

use aliases inside of an expression block can shadow names (module members or aliases) from the outer scope. As with shadowing of locals, the shadowing ends at the end of the expression block;

隐藏

在表达式块内使用别名可以隐藏外部范围的名称(模块成员或别名)。与局部变量的隐藏一样,阴影在表达式块的末尾结束;

address 0x42 {
module example {

    struct WrappedVector { vec: vector<u64> }

    fun empty(): WrappedVector {
        WrappedVector { vec: std::vector::empty() }
    }

    fun example1(): (WrappedVector, WrappedVector) {
        let vec = {
            use std::vector::{empty, push_back};
            // 'empty' now refers to std::vector::empty

            let v = empty();
            push_back(&mut v, 0);
            push_back(&mut v, 1);
            push_back(&mut v, 10);
            v
        };
        // 'empty' now refers to Self::empty

        (empty(), WrappedVector { vec })
    }

    fun example2(): (WrappedVector, WrappedVector) {
        use std::vector::{empty, push_back};
        let w: WrappedVector = {
            use 0x42::example::empty;
            empty()
        };
        push_back(&mut w.vec, 0);
        push_back(&mut w.vec, 1);
        push_back(&mut w.vec, 10);

        let vec = empty();
        push_back(&mut vec, 0);
        push_back(&mut vec, 1);
        push_back(&mut vec, 10);

        (w, WrappedVector { vec })
    }
}
}

Unused Use or Alias

An unused use will result in an error

未使用的使用或别名

未使用会导致错误

address 0x42 {
module example {
    use std::vector::{empty, push_back}; // ERROR!
    //                       ^^^^^^^^^ unused alias 'push_back'

    fun example(): vector<u8> {
        empty()
    }
}
}

Friends

The friend syntax is used to declare modules that are trusted by the current module. A trusted module is allowed to call any function defined in the current module that have the public(friend) visibility. For details on function visibilities, please refer to the Visibility section in Functions.

友元

友元语法用于声明当前模块信任的模块。允许受信任的模块调用当前模块中定义的任何具有公共(朋友)可见性的函数。有关函数可见性的详细信息,请参阅函数中的可见性部分。

Friend declaration

A module can declare other modules as friends via friend declaration statements, in the format of

  • friend <address::name> — friend declaration using fully qualified module name like the example below, or

友元声明

一个模块可以通过友元声明语句将其他模块声明为友元,格式为

  • friend <address::name> — 使用完全限定模块名称的朋友声明,如下例所示,或

    address 0x42 {
    module a {
        friend 0x42::b;
    }
    }
    
  • friend <module-name-alias> — friend declaration using a module name alias, where the module alias is introduced via the use statement.

  • friend <module-name-alias>——使用模块名称别名的朋友声明,其中模块别名是通过 use 语句引入的。

    address 0x42 {
    module a {
        use 0x42::b;
        friend b;
    }
    }
    

A module may have multiple friend declarations, and the union of all the friend modules forms the friend list. In the example below, both 0x42::B and 0x42::C are considered as friends of 0x42::A.

一个模块可能有多个好友声明,所有好友模块的并集形成好友列表。在下面的示例中,0x42::B 和 0x42::C 都被视为 0x42::A 的朋友。

address 0x42 {
module a {
    friend 0x42::b;
    friend 0x42::c;
}
}

Unlike use statements, friend can only be declared in the module scope and not in the expression block scope. friend declarations may be located anywhere a top-level construct (e.g., use, function, struct, etc.) is allowed. However, for readability, it is advised to place friend declarations near the beginning of the module definition.

Note that the concept of friendship does not apply to Move scripts:

  • A Move script cannot declare friend modules as doing so is considered meaningless: there is no mechanism to call the function defined in a script.
  • A Move module cannot declare friend scripts as well because scripts are ephemeral code snippets that are never published to global storage.

与 use 语句不同,friend 只能在模块范围内声明,而不能在表达式块范围内声明。友元声明可以位于允许顶级构造(例如,使用、函数、结构等)的任何地方。但是,为了可读性,建议将友元声明放在模块定义的开头附近。

请注意,友谊的概念不适用于 Move 脚本:

  • Move 脚本不能声明友元模块,因为这样做被认为是没有意义的:没有调用脚本中定义的函数的机制。
  • Move 模块也不能声明友元脚本,因为脚本是临时代码片段,从未发布到全局存储。

Friend declaration rules

Friend declarations are subject to the following rules:

  • A module cannot declare itself as a friend.

好友声明规则

朋友声明须遵守以下规则:

  • 模块不能将自己声明为友元。

    address 0x42 {
    module m { friend Self; // ERROR! }
    //                ^^^^ Cannot declare the module itself as a friend
    }
    
    address 0x43 {
    module m { friend 0x43::M; // ERROR! }
    //                ^^^^^^^ Cannot declare the module itself as a friend
    }
    
  • Friend modules must be known by the compiler

  • 编译器必须知道友元模块

    address 0x42 {
    module m { friend 0x42::nonexistent; // ERROR! }
    //                ^^^^^^^^^^^^^^^^^ Unbound module '0x42::nonexistent'
    }
    
  • Friend modules must be within the same account address. (Note: this is not a technical requirement but rather a policy decision which may be relaxed later.)

  • 好友模块必须在同一个账户地址内。 (注:这不是技术要求,而是以后可能放宽的政策决定。)

    address 0x42 {
    module m {}
    }
    
    address 0x43 {
    module n { friend 0x42::m; // ERROR! }
    //                ^^^^^^^ Cannot declare modules out of the current address as a friend
    }
    
  • Friends relationships cannot create cyclic module dependencies.

    Cycles are not allowed in the friend relationships, e.g., the relation 0x2::a friends 0x2::b friends 0x2::c friends 0x2::a is not allowed. More generally, declaring a friend module adds a dependency upon the current module to the friend module (because the purpose is for the friend to call functions in the current module). If that friend module is already used, either directly or transitively, a cycle of dependencies would be created.

  • 朋友关系不能创建循环模块依赖关系。

朋友关系中不允许循环,例如,关系 0x2::a 朋友 0x2::b 朋友 0x2::c 朋友 0x2::a 是不允许的。更一般地,声明一个友元模块会将对当前模块的依赖添加到友元模块(因为目的是让友元调用当前模块中的函数)。如果该友元模块已被直接或传递地使用,则将创建一个依赖循环。

address 0x2 {
module a {
    use 0x2::c;
    friend 0x2::b;

    public fun a() {
        c::c()
    }
}

module b {
    friend 0x2::c; // ERROR!
//         ^^^^^^ This friend relationship creates a dependency cycle: '0x2::b' is a friend of '0x2::a' uses '0x2::c' is a friend of '0x2::b'
}

module c {
    public fun c() {}
}
}
  • The friend list for a module cannot contain duplicates.

  • 模块的好友列表不能包含重复项。

    address 0x42 {
    module a {}
    
    module m {
        use 0x42::a as aliased_a;
        friend 0x42::A;
        friend aliased_a; // ERROR!
    //         ^^^^^^^^^ Duplicate friend declaration '0x42::a'. Friend declarations in a module must be unique
    }
    }
    

Packages

Packages allow Move programmers to more easily re-use code and share it across projects. The Move package system allows programmers to easily:

  • Define a package containing Move code;
  • Parameterize a package by named addresses;
  • Import and use packages in other Move code and instantiate named addresses;
  • Build packages and generate associated compilation artifacts from packages; and
  • Work with a common interface around compiled Move artifacts.

包

包允许 Move 程序员更轻松地重用代码并在项目之间共享。 Move 包系统允许程序员轻松地:

  • 定义一个包含移动代码的包;
  • 通过命名地址参数化包;
  • 在其他 Move 代码中导入和使用包并实例化命名地址;
  • 构建包并从包中生成相关的编译工件;和
  • 使用围绕已编译 Move 工件的通用接口。

Package Layout and Manifest Syntax

A Move package source directory contains a Move.toml package manifest file along with a set of subdirectories:

包布局和清单语法

Move 包源目录包含一个 Move.toml 包清单文件以及一组子目录:

a_move_package
├── Move.toml      (required)
├── sources        (required)
├── examples       (optional, test & dev mode)
├── scripts        (optional)
├── doc_templates  (optional)
└── tests          (optional, test mode)

The directories marked required must be present in order for the directory to be considered a Move package and to be compiled. Optional directories can be present, and if so will be included in the compilation process. Depending on the mode that the package is built with (test or dev), the tests and examples directories will be included as well.

The sources directory can contain both Move modules and Move scripts (both transaction scripts and modules containing script functions). The examples directory can hold additional code to be used only for development and/or tutorial purposes that will not be included when compiled outside test or dev mode.

A scripts directory is supported so transaction scripts can be separated from modules if that is desired by the package author. The scripts directory will always be included for compilation if it is present. Documentation will be built using any documentation templates present in the doc_templates directory.

必须存在标记为必需的目录才能将该目录视为 Move 包并进行编译。可以存在可选目录,如果存在,将包含在编译过程中。根据构建包的模式(测试或开发),测试和示例目录也将包括在内。

源目录可以包含移动模块和移动脚本(事务脚本和包含脚本函数的模块)。示例目录可以包含仅用于开发和/或教程目的的附加代码,这些代码在测试或开发模式之外编译时不会包含在内。

支持脚本目录,因此如果包作者需要,可以将事务脚本与模块分开。如果存在脚本目录,则将始终包含它以进行编译。将使用 doc_templates 目录中存在的任何文档模板构建文档。

Move.toml

The Move package manifest is defined within the Move.toml file and has the following syntax. Optional fields are marked with *, + denotes one or more elements:

Move 包清单在 Move.toml 文件中定义,并具有以下语法。可选字段标有 *,+ 表示一个或多个元素:

[package]
name = <string>                  # e.g., "MoveStdlib"
version = "<uint>.<uint>.<uint>" # e.g., "0.1.1"
license* = <string>              # e.g., "MIT", "GPL", "Apache 2.0"
authors* = [<string>]            # e.g., ["Joe Smith (joesmith@noemail.com)", "Jane Smith (janesmith@noemail.com)"]

[addresses]  # (Optional section) Declares named addresses in this package and instantiates named addresses in the package graph
# One or more lines declaring named addresses in the following format
<addr_name> = "_" | "<hex_address>" # e.g., std = "_" or my_addr = "0xC0FFEECAFE"

[dependencies] # (Optional section) Paths to dependencies and instantiations or renamings of named addresses from each dependency
# One or more lines declaring dependencies in the following format
<string> = { local = <string>, addr_subst* = { (<string> = (<string> | "<hex_address>"))+ } } # local dependencies
<string> = { git = <URL ending in .git>, subdir=<path to dir containing Move.toml inside git repo>, rev=<git commit hash>, addr_subst* = { (<string> = (<string> | "<hex_address>"))+ } } # git dependencies

[dev-addresses] # (Optional section) Same as [addresses] section, but only included in "dev" and "test" modes
# One or more lines declaring dev named addresses in the following format
<addr_name> = "_" | "<hex_address>" # e.g., std = "_" or my_addr = "0xC0FFEECAFE"

[dev-dependencies] # (Optional section) Same as [dependencies] section, but only included in "dev" and "test" modes
# One or more lines declaring dev dependencies in the following format
<string> = { local = <string>, addr_subst* = { (<string> = (<string> | <address>))+ } }

An example of a minimal package manifest with one local dependency and one git dependency:

具有一个本地依赖项和一个 git 依赖项的最小包清单示例:

[package]
name = "AName"
version = "0.0.0"

An example of a more standard package manifest that also includes the Move standard library and instantiates the named address Std from it with the address value 0x1:

一个更标准的包清单示例,它还包括 Move 标准库,并使用地址值 0x1 从中实例化命名地址 Std:

[package]
name = "AName"
version = "0.0.0"
license = "Apache 2.0"

[addresses]
address_to_be_filled_in = "_"
specified_address = "0xB0B"

[dependencies]
# Local dependency
LocalDep = { local = "projects/move-awesomeness", addr_subst = { "std" = "0x1" } }
# Git dependency
MoveStdlib = { git = "https://github.com/diem/diem.git", subdir="language/move-stdlib", rev = "56ab033cc403b489e891424a629e76f643d4fb6b" }

[dev-addresses] # For use when developing this module
address_to_be_filled_in = "0x101010101"

Most of the sections in the package manifest are self explanatory, but named addresses can be a bit difficult to understand so it's worth examining them in a bit more detail.

包清单中的大多数部分都是不言自明的,但命名地址可能有点难以理解,因此值得更详细地检查它们。

Named Addresses During Compilation

Recall that Move has named addresses and that named addresses cannot be declared in Move. Because of this, until now named addresses and their values needed to be passed to the compiler on the command line. With the Move package system this is no longer needed, and you can declare named addresses in the package, instantiate other named addresses in scope, and rename named addresses from other packages within the Move package system manifest file. Let's go through each of these individually:

编译期间的命名地址

回想一下,Move 具有命名地址,并且不能在 Move 中声明命名地址。因此,到目前为止,命名地址及其值都需要在命令行上传递给编译器。使用 Move 包系统,这不再需要,您可以在包中声明命名地址,实例化范围内的其他命名地址,并从 Move 包系统清单文件中的其他包重命名命名地址。让我们分别来看看这些:

Declaration

Let's say we have a Move module in example_pkg/sources/A.move as follows:

声明

假设我们在 example_pkg/sources/A.move 中有一个 Move 模块,如下所示:

module named_addr::A {
    public fun x(): address { @named_addr }
}

We could in example_pkg/Move.toml declare the named address named_addr in two different ways. The first:

我们可以在 example_pkg/Move.toml 中以两种不同的方式声明命名地址 named_addr。首先:

[package]
name = "ExamplePkg"
...
[addresses]
named_addr = "_"

Declares named_addr as a named address in the package ExamplePkg and that this address can be any valid address value. Therefore an importing package can pick the value of the named address named_addr to be any address it wishes. Intuitively you can think of this as parameterizing the package ExamplePkg by the named address named_addr, and the package can then be instantiated later on by an importing package.

named_addr can also be declared as:

将 named_addr 声明为包 ExamplePkg 中的命名地址,并且该地址可以是任何有效的地址值。因此,导入包可以选择命名地址 named_addr 的值作为它希望的任何地址。直观地,您可以将其视为通过命名地址named_addr参数化包ExamplePkg,然后可以稍后通过导入包来实例化该包。

named_addr 也可以声明为:

[package]
name = "ExamplePkg"
...
[addresses]
named_addr = "0xCAFE"

which states that the named address named_addr is exactly 0xCAFE and cannot be changed. This is useful so other importing packages can use this named address without needing to worry about the exact value assigned to it.

With these two different declaration methods, there are two ways that information about named addresses can flow in the package graph:

  • The former ("unassigned named addresses") allows named address values to flow from the importation site to the declaration site.
  • The latter ("assigned named addresses") allows named address values to flow from the declaration site upwards in the package graph to usage sites.

With these two methods for flowing named address information throughout the package graph the rules around scoping and renaming become important to understand.

其中指出命名地址 named_addr 正好是 0xCAFE 并且不能更改。这很有用,因此其他导入包可以使用这个命名地址,而无需担心分配给它的确切值。

使用这两种不同的声明方法,有关命名地址的信息可以通过两种方式在包图中流动:

  • 前者(“未分配的命名地址”)允许命名地址值从进口站点流向申报站点。
  • 后者(“分配的命名地址”)允许命名地址值从包图中的声明站点向上流动到使用站点。

通过这两种在整个包图中流动命名地址信息的方法,了解范围和重命名的规则变得很重要。

Scoping and Renaming of Named Addresses

A named address N in a package P is in scope if:

  1. It declares a named address N; or
  2. A package in one of P's transitive dependencies declares the named address N and there is a dependency path in the package graph between between P and the declaring package of N with no renaming of N.

Additionally, every named address in a package is exported. Because of this and the above scoping rules each package can be viewed as coming with a set of named addresses that will be brought into scope when the package is imported, e.g., if the ExamplePkg package was imported, that importation would bring into scope the named_addr named address. Because of this, if P imports two packages P1 and P2 both of which declare a named address N an issue arises in P: which "N" is meant when N is referred to in P? The one from P1 or P2? To prevent this ambiguity around which package a named address is coming from, we enforce that the sets of scopes introduced by all dependencies in a package are disjoint, and provide a way to rename named addresses when the package that brings them into scope is imported.

Renaming a named address when importing can be done as follows in our P, P1, and P2 example above:

命名地址的范围和重命名

包 P 中的命名地址 N 在范围内,如果:

  1. 它声明了一个命名地址N;或者
  2. P 的传递依赖项之一中的包声明了命名地址 N,并且在 P 和声明 N 的包之间的包图中存在一条依赖路径,没有重命名 N。

此外,包中的每个命名地址都会被导出。由于这个和上述范围规则,每个包都可以被视为带有一组命名地址,这些地址将在导入包时被纳入范围,例如,如果导入了 ExamplePkg 包,则该导入会将 named_addr 纳入范围命名地址。正因为如此,如果 P 导入两个包 P1 和 P2,这两个包都声明了一个命名地址 N,那么 P 中就会出现问题:当 P 中引用 N 时,哪个“N”是指? P1还是P2的那个?为了防止命名地址来自哪个包的这种歧义,我们强制一个包中所有依赖项引入的范围集是不相交的,并提供一种在将命名地址带入范围的包被导入时重命名命名地址的方法。

在我们上面的 P、P1 和 P2 示例中,可以在导入时重命名命名地址,如下所示:

[package]
name = "P"
...
[dependencies]
P1 = { local = "some_path_to_P1", addr_subst = { "P1N" = "N" } }
P2 = { local = "some_path_to_P2"  }

With this renaming N refers to the N from P2 and P1N will refer to N coming from P1:

通过这个重命名,N 指的是来自 P2 的 N,而 P1N 将指的是来自 P1 的 N:

module N::A {
    public fun x(): address { @P1N }
}

It is important to note that renaming is not local: once a named address N has been renamed to N2 in a package P all packages that import P will not see N but only N2 unless N is reintroduced from outside of P. This is why rule (2) in the scoping rules at the start of this section specifies a "dependency path in the package graph between between P and the declaring package of N with no renaming of N."

重要的是要注意重命名不是本地的:一旦在包 P 中将命名地址 N 重命名为 N2,所有导入 P 的包都不会看到 N,而只会看到 N2,除非从 P 外部重新引入 N。这就是为什么规则(2) 在本节开头的作用域规则中指定了“包图中 P 和 N 的声明包之间的依赖路径,没有重命名 N。”

Instantiation

Named addresses can be instantiated multiple times across the package graph as long as it is always with the same value. It is an error if the same named address (regardless of renaming) is instantiated with differing values across the package graph.

A Move package can only be compiled if all named addresses resolve to a value. This presents issues if the package wishes to expose an uninstantiated named address. This is what the [dev-addresses] section solves. This section can set values for named addresses, but cannot introduce any named addresses. Additionally, only the [dev-addresses] in the root package are included in dev mode. For example a root package with the following manifest would not compile outside of dev mode since named_addr would be uninstantiated:

实例化

只要命名地址始终具有相同的值,就可以在包图中多次实例化命名地址。如果在整个包图中使用不同的值实例化相同的命名地址(无论是否重命名),则会出现错误。

只有当所有命名地址都解析为一个值时,才能编译 Move 包。如果包希望公开未实例化的命名地址,则会出现问题。这就是 [dev-addresses] 部分解决的问题。本节可以设置命名地址的值,但不能引入任何命名地址。此外,只有根包中的 [dev-addresses] 包含在开发模式中。例如,具有以下清单的根包不会在开发模式之外编译,因为 named_addr 将未实例化:

[package]
name = "ExamplePkg"
...
[addresses]
named_addr = "_"

[dev-addresses]
named_addr = "0xC0FFEE"

Usage, Artifacts, and Data Structures

The Move package system comes with a command line option as part of the Move CLI move <flags> <command> <command_flags>. Unless a particular path is provided, all package commands will run in the current working directory. The full list of commands and flags for the Move CLI can be found by running move --help.

用法、工件和数据结构

Move 包系统附带一个命令行选项,作为 Move CLI 移动标志命令 command_flags 的一部分。除非提供特定路径,否则所有包命令都将在当前工作目录中运行。可以通过运行 move --help 找到 Move CLI 的命令和标志的完整列表。

Usage

A package can be compiled either through the Move CLI commands, or as a library command in Rust with the function compile_package. This will create a CompiledPackage that holds the compiled bytecode along with other compilation artifacts (source maps, documentation, ABIs) in memory. This CompiledPackage can be converted to an OnDiskPackage and vice versa -- the latter being the data of the CompiledPackage laid out in the file system in the following format:

用法

可以通过 Move CLI 命令编译包,也可以使用函数 compile_package 在 Rust 中编译为库命令。这将创建一个 CompiledPackage,它在内存中保存已编译的字节码以及其他编译工件(源映射、文档、ABI)。这个 CompiledPackage 可以转换为 OnDiskPackage ,反之亦然 - 后者是 CompiledPackage 的数据,以下列格式在文件系统中布局:

a_move_package
├── Move.toml
...
└── build
    ├── <dep_pkg_name>
    │   ├── BuildInfo.yaml
    │   ├── bytecode_modules
    │   │   └── *.mv
    │   ├── source_maps
    │   │   └── *.mvsm
    │   ├── bytecode_scripts
    │   │   └── *.mv
    │   ├── abis
    │   │   ├── *.abi
    │   │   └── <module_name>/*.abi
    │   └── sources
    │       └── *.move
    ...
    └── <dep_pkg_name>
        ├── BuildInfo.yaml
        ...
        └── sources

See the move-package crate for more information on these data structures and how to use the Move package system as a Rust library.

有关这些数据结构以及如何将 Move 包系统用作 Rust 库的更多信息,请参阅 move-package crate。

Unit Tests

Unit testing for Move adds three new annotations to the Move source language:

  • #[test]
  • #[test_only], and
  • #[expected_failure].

They respectively mark a function as a test, mark a module or module member (use, function, or struct) as code to be included for testing only, and mark that a test is expected to fail. These annotations can be placed on a function with any visibility. Whenever a module or module member is annotated as #[test_only] or #[test], it will not be included in the compiled bytecode unless it is compiled for testing.

单元测试

Move 的单元测试为 Move 源语言添加了三个新注释:

  • #[test]
  • #[test_only],和
  • #[expected_failure]。

它们分别将函数标记为测试,将模块或模块成员(使用、函数或结构)标记为仅用于测试的代码,并标记预期测试将失败。这些注释可以放置在具有任何可见性的函数上。每当一个模块或模块成员被注释为 #[test_only] 或 #[test] 时,它不会包含在编译的字节码中,除非它被编译用于测试。

Testing Annotations: Their Meaning and Usage

Both the #[test] and #[expected_failure] annotations can be used either with or without arguments.

Without arguments, the #[test] annotation can only be placed on a function with no parameters. This annotation simply marks this function as a test to be run by the unit testing harness.

测试注释:它们的含义和用法

#[test] 和 #[expected_failure] 注释都可以带或不带参数使用。

没有参数,#[test] 注释只能放在没有参数的函数上。此注释只是将此函数标记为要由单元测试工具运行的测试。

#[test] // OK
fun this_is_a_test() { ... }

#[test] // Will fail to compile since the test takes an argument
fun this_is_not_correct(arg: signer) { ... }

A test can also be annotated as an #[expected_failure]. This annotation marks that the test should is expected to raise an error. You can ensure that a test is aborting with a specific abort code by annotating it with #[expected_failure(abort_code = <code>)], if it then fails with a different abort code or with a non-abort error the test will fail. Only functions that have the #[test] annotation can also be annotated as an #[expected_failure].

测试也可以注释为 #[expected_failure]。此注释标志着测试应该会引发错误。您可以通过使用 #[expected_failure(abort_code = code)] 对其进行注释来确保测试使用特定的中止代码中止,如果它随后因不同的中止代码或非中止错误而失败,则测试将失败。只有具有 #[test] 注释的函数也可以注释为 #[expected_failure]。

#[test]
#[expected_failure]
public fun this_test_will_abort_and_pass() { abort 1 }

#[test]
#[expected_failure]
public fun test_will_error_and_pass() { 1/0; }

#[test]
#[expected_failure(abort_code = 0)]
public fun test_will_error_and_fail() { 1/0; }

#[test, expected_failure] // Can have multiple in one attribute. This test will pass.
public fun this_other_test_will_abort_and_pass() { abort 1 }

With arguments, a test annotation takes the form #[test(<param_name_1> = <address>, ..., <param_name_n> = <address>)]. If a function is annotated in such a manner, the function's parameters must be a permutation of the parameters <param_name_1>, ..., <param_name_n>, i.e., the order of these parameters as they occur in the function and their order in the test annotation do not have to be the same, but they must be able to be matched up with each other by name.

Only parameters with a type of signer are supported as test parameters. If a non-signer parameter is supplied, the test will result in an error when run.

带有参数的测试注解采用 #[test( param_name_1 = address , ..., param_name_n = address )] 的形式。如果以这种方式注释函数,则函数的参数必须是参数 param_name_1 , ..., param_name_n 的排列,即这些参数在函数中出现的顺序和它们在测试注释中的顺序不必须相同,但它们必须能够通过名称相互匹配。

仅支持具有签名者类型的参数作为测试参数。如果提供了非签名者参数,则测试将在运行时导致错误。

#[test(arg = @0xC0FFEE)] // OK
fun this_is_correct_now(arg: signer) { ... }

#[test(wrong_arg_name = @0xC0FFEE)] // Not correct: arg name doesn't match
fun this_is_incorrect(arg: signer) { ... }

#[test(a = @0xC0FFEE, b = @0xCAFE)] // OK. We support multiple signer arguments, but you must always provide a value for that argument
fun this_works(a: signer, b: signer) { ... }

// somewhere a named address is declared
#[test_only] // test-only named addresses are supported
address TEST_NAMED_ADDR = @0x1;
...
#[test(arg = @TEST_NAMED_ADDR)] // Named addresses are supported!
fun this_is_correct_now(arg: signer) { ... }

An expected failure annotation can also take the form #[expected_failure(abort_code = <u64>)]. If a test function is annotated in such a way, the test must abort with an abort code equal to <u64>. Any other failure or abort code will result in a test failure.

预期的失败注释也可以采用 #[expected_failure(abort_code = u64)] 的形式。如果以这种方式注释测试函数,则必须使用等于 u64 的中止代码中止测试。任何其他失败或中止代码都将导致测试失败。

#[test, expected_failure(abort_code = 1)] // This test will fail
fun this_test_should_abort_and_fail() { abort 0 }

#[test]
#[expected_failure(abort_code = 0)] // This test will pass
fun this_test_should_abort_and_pass_too() { abort 0 }

A module and any of its members can be declared as test only. In such a case the item will only be included in the compiled Move bytecode when compiled in test mode. Additionally, when compiled outside of test mode, any non-test uses of a #[test_only] module will raise an error during compilation.

一个模块及其任何成员都可以声明为仅测试。在这种情况下,只有在测试模式下编译时,该项目才会包含在编译后的 Move 字节码中。此外,在测试模式之外编译时,#[test_only] 模块的任何非测试使用都会在编译期间引发错误。

#[test_only] // test only attributes can be attached to modules
module abc { ... }

#[test_only] // test only attributes can be attached to named addresses
address ADDR = @0x1;

#[test_only] // .. to uses
use 0x1::some_other_module;

#[test_only] // .. to structs
struct SomeStruct { ... }

#[test_only] // .. and functions. Can only be called from test code, but not a test
fun test_only_function(...) { ... }

Running Unit Tests

Unit tests for a Move package can be run with the move test command.

When running tests, every test will either PASS, FAIL, or TIMEOUT. If a test case fails, the location of the failure along with the function name that caused the failure will be reported if possible. You can see an example of this below.

A test will be marked as timing out if it exceeds the maximum number of instructions that can be executed for any single test. This bound can be changed using the options below, and its default value is set to 5000 instructions. Additionally, while the result of a test is always deterministic, tests are run in parallel by default, so the ordering of test results in a test run is non-deterministic unless running with only one thread (see OPTIONS below).

There are also a number of options that can be passed to the unit testing binary to fine-tune testing and to help debug failing tests. These can be found using the the help flag:

运行单元测试

可以使用 move test 命令运行 Move 包的单元测试。

运行测试时,每个测试都将通过、失败或超时。如果测试用例失败,将尽可能报告失败的位置以及导致失败的函数名称。您可以在下面看到一个示例。

如果测试超过任何单个测试可以执行的最大指令数,则测试将被标记为超时。可以使用以下选项更改此界限,其默认值设置为 5000 条指令。此外,虽然测试的结果始终是确定性的,但默认情况下测试是并行运行的,因此测试运行中测试结果的顺序是不确定的,除非仅使用一个线程运行(请参阅下面的选项)。

还有许多选项可以传递给单元测试二进制文件以微调测试并帮助调试失败的测试。这些可以使用帮助标志找到:

$ move -h

Example

A simple module using some of the unit testing features is shown in the following example:

First create an empty package and change directory into it:

例子

以下示例显示了使用一些单元测试功能的简单模块:

首先创建一个空包并将目录更改为它:

$ move new TestExample; cd TestExample

Next add the following to the Move.toml:

接下来将以下内容添加到 Move.toml:

[dependencies]
MoveStdlib = { git = "https://github.com/diem/diem.git", subdir="language/move-stdlib", rev = "56ab033cc403b489e891424a629e76f643d4fb6b", addr_subst = { "std" = "0x1" } }

Next add the following module under the sources directory:

接下来在源目录下添加以下模块:

// filename: sources/my_module.move
module 0x1::my_module {

    struct MyCoin has key { value: u64 }

    public fun make_sure_non_zero_coin(coin: MyCoin): MyCoin {
        assert!(coin.value > 0, 0);
        coin
    }

    public fun has_coin(addr: address): bool {
        exists<MyCoin>(addr)
    }

    #[test]
    fun make_sure_non_zero_coin_passes() {
        let coin = MyCoin { value: 1 };
        let MyCoin { value: _ } = make_sure_non_zero_coin(coin);
    }

    #[test]
    // Or #[expected_failure] if we don't care about the abort code
    #[expected_failure(abort_code = 0)]
    fun make_sure_zero_coin_fails() {
        let coin = MyCoin { value: 0 };
        let MyCoin { value: _ } = make_sure_non_zero_coin(coin);
    }

    #[test_only] // test only helper function
    fun publish_coin(account: &signer) {
        move_to(account, MyCoin { value: 1 })
    }

    #[test(a = @0x1, b = @0x2)]
    fun test_has_coin(a: signer, b: signer) {
        publish_coin(&a);
        publish_coin(&b);
        assert!(has_coin(@0x1), 0);
        assert!(has_coin(@0x2), 1);
        assert!(!has_coin(@0x3), 1);
    }
}

Running Tests

You can then run these tests with the move test command:

运行测试

然后,您可以使用 move test 命令运行这些测试:

$ move test
BUILDING MoveStdlib
BUILDING TestExample
Running Move unit tests
[ PASS    ] 0x1::my_module::make_sure_non_zero_coin_passes
[ PASS    ] 0x1::my_module::make_sure_zero_coin_fails
[ PASS    ] 0x1::my_module::test_has_coin
Test result: OK. Total tests: 3; passed: 3; failed: 0

Using Test Flags

-f <str> or --filter <str>

This will only run tests whose fully qualified name contains <str>. For example if we wanted to only run tests with "zero_coin" in their name:

使用测试标志

-f <str> 或 --filter <str>

这只会运行完全限定名称包含 str 的测试。例如,如果我们只想运行名称中带有“zero_coin”的测试:

$ move test -f zero_coin
CACHED MoveStdlib
BUILDING TestExample
Running Move unit tests
[ PASS    ] 0x1::my_module::make_sure_non_zero_coin_passes
[ PASS    ] 0x1::my_module::make_sure_zero_coin_fails
Test result: OK. Total tests: 2; passed: 2; failed: 0

-i <bound> or --instructions <bound>

This bounds the number of instructions that can be executed for any one test to <bound>:

-i <bound> 或 --instructions <bound>

这将任何一个测试可以执行的指令数限制为 bound :

$ move test -i 0
CACHED MoveStdlib
BUILDING TestExample
Running Move unit tests
[ TIMEOUT ] 0x1::my_module::make_sure_non_zero_coin_passes
[ TIMEOUT ] 0x1::my_module::make_sure_zero_coin_fails
[ TIMEOUT ] 0x1::my_module::test_has_coin

Test failures:

Failures in 0x1::my_module:

┌── make_sure_non_zero_coin_passes ──────
│ Test timed out
└──────────────────


┌── make_sure_zero_coin_fails ──────
│ Test timed out
└──────────────────


┌── test_has_coin ──────
│ Test timed out
└──────────────────

Test result: FAILED. Total tests: 3; passed: 0; failed: 3

-s or --statistics

With these flags you can gather statistics about the tests run and report the runtime and instructions executed for each test. For example, if we wanted to see the statistics for the tests in the example above:

-s 或 --statistics

使用这些标志,您可以收集有关测试运行的统计信息,并报告每个测试的运行时间和执行的指令。例如,如果我们想查看上例中测试的统计信息:

$ move test -s
CACHED MoveStdlib
BUILDING TestExample
Running Move unit tests
[ PASS    ] 0x1::my_module::make_sure_non_zero_coin_passes
[ PASS    ] 0x1::my_module::make_sure_zero_coin_fails
[ PASS    ] 0x1::my_module::test_has_coin

Test Statistics:

┌────────────────────────────────────────────────┬────────────┬───────────────────────────┐
│                   Test Name                    │    Time    │   Instructions Executed   │
├────────────────────────────────────────────────┼────────────┼───────────────────────────┤
│ 0x1::my_module::make_sure_non_zero_coin_passes │   0.009    │             1             │
├────────────────────────────────────────────────┼────────────┼───────────────────────────┤
│ 0x1::my_module::make_sure_zero_coin_fails      │   0.008    │             1             │
├────────────────────────────────────────────────┼────────────┼───────────────────────────┤
│ 0x1::my_module::test_has_coin                  │   0.008    │             1             │
└────────────────────────────────────────────────┴────────────┴───────────────────────────┘

Test result: OK. Total tests: 3; passed: 3; failed: 0

-g or --state-on-error

These flags will print the global state for any test failures. e.g., if we added the following (failing) test to the my_module example:

-g 或 --state-on-error

这些标志将打印任何测试失败的全局状态。例如,如果我们将以下(失败)测试添加到 my_module 示例中:

module 0x1::my_module {
    ...
    #[test(a = @0x1)]
    fun test_has_coin_bad(a: signer) {
        publish_coin(&a);
        assert!(has_coin(@0x1), 0);
        assert!(has_coin(@0x2), 1);
    }
}

we would get get the following output when running the tests:

运行测试时我们会得到以下输出:

$ move test -g
CACHED MoveStdlib
BUILDING TestExample
Running Move unit tests
[ PASS    ] 0x1::my_module::make_sure_non_zero_coin_passes
[ PASS    ] 0x1::my_module::make_sure_zero_coin_fails
[ PASS    ] 0x1::my_module::test_has_coin
[ FAIL    ] 0x1::my_module::test_has_coin_bad

Test failures:

Failures in 0x1::my_module:

┌── test_has_coin_bad ──────
│ error[E11001]: test failure
│    ┌─ /home/tzakian/TestExample/sources/my_module.move:47:10
│    │
│ 44 │      fun test_has_coin_bad(a: signer) {
│    │          ----------------- In this function in 0x1::my_module
│    ·
│ 47 │          assert!(has_coin(@0x2), 1);
│    │          ^^^^^^^^^^^^^^^^^^^^^^^^^^ Test was not expected to abort but it aborted with 1 here
│
│
│ ────── Storage state at point of failure ──────
│ 0x1:
│       => key 0x1::my_module::MyCoin {
│           value: 1
│       }
│
└──────────────────

Test result: FAILED. Total tests: 4; passed: 3; failed: 1

全局存储 —— 结构

Move 程序的目的是读取和写入树形的持久全局存储。程序不能访问文件系统、网络或任何此树以外的数据。

在伪代码中,全局存储看起来像:

struct GlobalStorage {
  resources: Map<(address, ResourceType), ResourceValue>
  modules: Map<(address, ModuleName), ModuleBytecode>
}

从结构上讲,全局存储是一个森林(forest),这个森林由以账户地址(address)为根的树组成。每个地址可以存储资源(resource)数据和模块(module)代码。如上面的伪代码所示,每个地址(address)最多可以存储一个给定类型的资源值,最多可以存储一个给定名称的模块。

Global Storage - Operators

Move programs can create, delete, and update resources in global storage using the following five instructions:

全球存储 - 操作符

移动程序可以使用以下五个指令在全局存储中创建、删除和更新资源:

OperationDescriptionAborts?
move_to<T>(&signer,T)Publish T under signer.addressIf signer.address already holds a T
move_from<T>(address): TRemove T from address and return itIf address does not hold a T
borrow_global_mut<T>(address): &mut TReturn a mutable reference to the T stored under addressIf address does not hold a T
borrow_global<T>(address): &TReturn an immutable reference to the T stored under addressIf address does not hold a T
exists<T>(address): boolReturn true if a T is stored under addressNever

Each of these instructions is parameterized by a type T with the key ability. However, each type T must be declared in the current module. This ensures that a resource can only be manipulated via the API exposed by its defining module. The instructions also take either an address or &signer representing the account address where the resource of type T is stored.

这些指令中的每一个都由具有关键能力的类型 T 参数化。但是,每个类型 T 都必须在当前模块中声明。这确保了资源只能通过其定义模块公开的 API 进行操作。这些指令还采用地址或 &signer 表示存储类型 T 资源的帐户地址。

References to resources

References to global resources returned by borrow_global or borrow_global_mut mostly behave like references to local storage: they can be extended, read, and written using ordinary reference operators and passed as arguments to other function. However, there is one important difference between local and global references: a function cannot return a reference that points into global storage. For example, these two functions will each fail to compile:

对资源的引用

borrow_global 或 borrow_global_mut 返回的对全局资源的引用主要表现为对本地存储的引用:它们可以使用普通的引用运算符进行扩展、读取和写入,并作为参数传递给其他函数。但是,本地引用和全局引用之间有一个重要区别:函数不能返回指向全局存储的引用。例如,这两个函数都将无法编译:

struct R has key { f: u64 }
// will not compile
fun ret_direct_resource_ref_bad(a: address): &R {
    borrow_global<R>(a) // error!
}
// also will not compile
fun ret_resource_field_ref_bad(a: address): &u64 {
    &borrow_global<R>(a).f // error!
}

Move must enforce this restriction to guarantee absence of dangling references to global storage. This section contains much more detail for the interested reader.

Move 必须强制执行此限制以保证不存在对全局存储的悬空引用。本节为感兴趣的读者提供了更多详细信息。

Global storage operators with generics

Global storage operations can be applied to generic resources with both instantiated and uninstantiated generic type parameters:

具有泛型的全局存储运算符

全局存储操作可以应用于具有实例化和未实例化的泛型类型参数的泛型资源:

struct Container<T> has key { t: T }

// Publish a Container storing a type T of the caller's choosing
fun publish_generic_container<T>(account: &signer, t: T) {
    move_to<Container<T>>(account, Container { t })
}

/// Publish a container storing a u64
fun publish_instantiated_generic_container(account: &signer, t: u64) {
    move_to<Container<u64>>(account, Container { t })
}

The ability to index into global storage via a type parameter chosen at runtime is a powerful Move feature known as storage polymorphism. For more on the design patterns enabled by this feature, see Move generics.

通过在运行时选择的类型参数对全局存储进行索引的能力是一种强大的移动功能,称为存储多态性。有关此功能启用的设计模式的更多信息,请参阅移动泛型。

Example: Counter

The simple Counter module below exercises each of the five global storage operators. The API exposed by this module allows:

  • Anyone to publish a Counter resource under their account
  • Anyone to check if a Counter exists under any address
  • Anyone to read or increment the value of a Counter resource under any address
  • An account that stores a Counter resource to reset it to zero
  • An account that stores a Counter resource to remove and delete it

示例:计数器

下面的简单 Counter 模块练习了五个全局存储运算符中的每一个。该模块公开的 API 允许:

  • 任何人都可以在其帐户下发布 Counter 资源
  • 任何人都可以检查任何地址下是否存在计数器
  • 任何人都可以读取或增加任何地址下的 Counter 资源的值
  • 存储计数器资源以将其重置为零的帐户
  • 存储 Counter 资源以移除和删除它的帐户
address 0x42 {
module counter {
    use std::signer;

    /// Resource that wraps an integer counter
    struct Counter has key { i: u64 }

    /// Publish a `Counter` resource with value `i` under the given `account`
    public fun publish(account: &signer, i: u64) {
      // "Pack" (create) a Counter resource. This is a privileged operation that
      // can only be done inside the module that declares the `Counter` resource
      move_to(account, Counter { i })
    }

    /// Read the value in the `Counter` resource stored at `addr`
    public fun get_count(addr: address): u64 acquires Counter {
        borrow_global<Counter>(addr).i
    }

    /// Increment the value of `addr`'s `Counter` resource
    public fun increment(addr: address) acquires Counter {
        let c_ref = &mut borrow_global_mut<Counter>(addr).i;
        *c_ref = *c_ref + 1
    }

    /// Reset the value of `account`'s `Counter` to 0
    public fun reset(account: &signer) acquires Counter {
        let c_ref = &mut borrow_global_mut<Counter>(signer::address_of(account)).i;
        *c_ref = 0
    }

    /// Delete the `Counter` resource under `account` and return its value
    public fun delete(account: &signer): u64 acquires Counter {
        // remove the Counter resource
        let c = move_from<Counter>(signer::address_of(account));
        // "Unpack" the `Counter` resource into its fields. This is a
        // privileged operation that can only be done inside the module
        // that declares the `Counter` resource
        let Counter { i } = c;
        i
    }

    /// Return `true` if `addr` contains a `Counter` resource
    public fun exists(addr: address): bool {
        exists<Counter>(addr)
    }
}
}

Annotating functions with acquires

In the counter example, you might have noticed that the get_count, increment, reset, and delete functions are annotated with acquires Counter. A Move function m::f must be annotated with acquires T if and only if:

  • The body of m::f contains a move_from<T>, borrow_global_mut<T>, or borrow_global<T> instruction, or
  • The body of m::f invokes a function m::g declared in the same module that is annotated with acquires

For example, the following function inside Counter would need an acquires annotation:

使用获取注释函数

在 counter 示例中,您可能已经注意到 get_count、increment、reset 和 delete 函数都使用 acquire Counter 进行注释。移动函数 m::f 必须用获取 T 注释当且仅当:

  • m::f 的主体包含 move_from T 、 borrow_global_mut T 或 borrow_global T 指令,或
  • m::f 的主体调用在同一个模块中声明的函数 m::g 例如,Counter 中的以下函数需要一个获取注解:
// Needs `acquires` because `increment` is annotated with `acquires`
fun call_increment(addr: address): u64 acquires Counter {
    counter::increment(addr)
}

However, the same function outside Counter would not need an annotation:

但是,Counter 之外的相同函数不需要注释:

address 0x43 {
module m {
   use 0x42::counter;

   // Ok. Only need annotation when resource acquired by callee is declared
   // in the same module
   fun call_increment(addr: address): u64 {
       counter::increment(addr)
   }
}
}

If a function touches multiple resources, it needs multiple acquires:

如果一个函数涉及多个资源,它需要多次获取:

address 0x42 {
module two_resources {
    struct R1 has key { f: u64 }
    struct R2 has key { g: u64 }

    fun double_acquires(a: address): u64 acquires R1, R2 {
        borrow_global<R1>(a).f + borrow_global<R2>.g
    }
}
}

The acquires annotation does not take generic type parameters into account:

获取注解不考虑泛型类型参数:

address 0x42 {
module m {
    struct R<T> has key { t: T }

    // `acquires R`, not `acquires R<T>`
    fun acquire_generic_resource<T: store>(a: addr) acquires R {
        let _ = borrow_global<R<T>>(a);
    }

    // `acquires R`, not `acquires R<u64>
    fun acquire_instantiated_generic_resource(a: addr) acquires R {
        let _ = borrow_global<R<u64>>(a);
    }
}
}

Finally: redundant acquires are not allowed. Adding this function inside Counter will result in a compilation error:

最后:不允许冗余获取。在 Counter 中添加这个函数会导致编译错误:

// This code will not compile because the body of the function does not use a global
// storage instruction or invoke a function with `acquires`
fun redundant_acquires_bad() acquires Counter {}

For more information on acquires, see Move functions.

有关获取的更多信息,请参阅移动函数。

Reference Safety For Global Resources

Move prohibits returning global references and requires the acquires annotation to prevent dangling references. This allows Move to live up to its promise of static reference safety (i.e., no dangling references, no null or nil dereferences) for all reference types.

This example illustrates how the Move type system uses acquires to prevent a dangling reference:

全局资源的引用安全

Move 禁止返回全局引用,并要求获取注解以防止悬空引用。这允许 Move 兑现其对所有引用类型的静态引用安全的承诺(即,没有悬空引用,没有 null 或 nil 取消引用)。

此示例说明了 Move 类型系统如何使用获取来防止悬空引用:

address 0x42 {
module dangling {
    struct T has key { f: u64 }

    fun borrow_then_remove_bad(a: address) acquires T {
        let t_ref: &mut T = borrow_global_mut<T>(a);
        let t = remove_t(a); // type system complains here
        // t_ref now dangling!
        let uh_oh = *&t_ref.f
    }

    fun remove_t(a: address): T acquires T {
        move_from<T>(a)
    }

}
}

In this code, line 6 acquires a reference to the T stored at address a in global storage. The callee remove_t then removes the value, which makes t_ref a dangling reference.

Fortunately, this cannot happen because the type system will reject this program. The acquires annotation on remove_t lets the type system know that line 7 is dangerous, without having to recheck or introspect the body of remove_t separately!

The restriction on returning global references prevents a similar, but even more insidious problem:

在此代码中,第 6 行获取对存储在全局存储中地址 a 处的 T 的引用。被调用者 remove_t 然后删除该值,这使 t_ref 成为悬空引用。

幸运的是,这不可能发生,因为类型系统会拒绝这个程序。 remove_t 上的 acquires 注释让类型系统知道第 7 行是危险的,而无需单独重新检查或反省 remove_t 的主体!

对返回全局引用的限制防止了类似但更隐蔽的问题:

address 0x42 {
module m1 {
    struct T has key {}

    public fun ret_t_ref(a: address): &T acquires T {
        borrow_global<T>(a) // error! type system complains here
    }

    public fun remove_t(a: address) acquires T {
        let T {} = move_from<T>(a);
    }
}

module m2 {
    fun borrow_then_remove_bad(a: address) {
        let t_ref = m1::ret_t_ref(a);
        let t = m1::remove_t(a); // t_ref now dangling!
    }
}
}

Line 16 acquires a reference to a global resource m1::T, then line 17 removes that same resource, which makes t_ref dangle. In this case, acquires annotations do not help us because the borrow_then_remove_bad function is outside of the m1 module that declares T (recall that acquires annotations can only be used for resources declared in the current module). Instead, the type system avoids this problem by preventing the return of a global reference at line 6.

Fancier type systems that would allow returning global references without sacrificing reference safety are possible, and we may consider them in future iterations of Move. We chose the current design because it strikes a good balance between expressivity, annotation burden, and type system complexity.

第 16 行获取对全局资源 m1::T 的引用,然后第 17 行删除相同的资源,这使得 t_ref 悬空。在这种情况下,获取注解对我们没有帮助,因为 borrow_then_remove_bad 函数位于声明 T 的 m1 模块之外(回想一下,获取注解只能用于在当前模块中声明的资源)。相反,类型系统通过阻止在第 6 行返回全局引用来避免这个问题。

在不牺牲引用安全的情况下允许返回全局引用的更高级的类型系统是可能的,我们可能会在 Move 的未来迭代中考虑它们。我们选择了当前的设计,因为它在表现力、注释负担和类型系统复杂性之间取得了很好的平衡。

Standard Library

The Move standard library exposes interfaces that implement the following functionality:

标准库

Move 标准库公开了实现以下功能的接口:

  • 向量的基本操作。
  • 选项类型和选项类型的操作。
  • 中止代码的常见错误编码代码接口。
  • 32 位精度定点数。

vector

The vector module defines a number of operations over the primitive vector type. The module is published under the named address Std and consists of a number of native functions, as well as functions defined in Move. The API for this module is as follows.

向量

vector 模块定义了对原始向量类型的许多操作。该模块在命名地址 Std 下发布,由许多本机函数以及 Move 中定义的函数组成。该模块的 API 如下。

Functions

函数


Create an empty vector. The Element type can be both a resource or copyable type.

创建一个空向量。 Element 类型既可以是资源类型,也可以是可复制类型。

    native public fun empty<Element>(): vector<Element>;

Create a vector of length 1 containing the passed in element.

创建一个包含传入元素的长度为 1 的向量。

    public fun singleton<Element>(e: Element): vector<Element>;

Destroy (deallocate) the vector v. Will abort if v is non-empty. Note: The emptiness restriction is due to the fact that Element can be a resource type, and destruction of a non-empty vector would violate resource conservation.

销毁(解除分配)向量 v。如果 v 不为空,将中止。注意:空性限制是由于 Element 可以是资源类型,销毁非空向量会违反资源守恒。

    native public fun destroy_empty<Element>(v: vector<Element>);

Acquire an immutable reference to the ith element of the vector v. Will abort if the index i is out of bounds for the vector v.

获取对向量 v 的第 i 个元素的不可变引用。如果索引 i 超出向量 v 的范围,将中止。

    native public fun borrow<Element>(v: &vector<Element>, i: u64): &Element;

Acquire a mutable reference to the ith element of the vector v. Will abort if the index i is out of bounds for the vector v.

获取对向量 v 的第 i 个元素的可变引用。如果索引 i 超出向量 v 的范围,将中止。

    native public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element;

Empty and destroy the other vector, and push each of the elements in the other vector onto the lhs vector in the same order as they occurred in other.

清空并销毁另一个向量,并将另一个向量中的每个元素以与它们在其他向量中出现的顺序相同的顺序推送到 lhs 向量上。

    public fun append<Element>(lhs: &mut vector<Element>, other: vector<Element>);

Push an element e of type Element onto the end of the vector v. May trigger a resizing of the underlying vector's memory.

将 Element 类型的元素 e 推到向量 v 的末尾。可能会触发底层向量内存的大小调整。

    native public fun push_back<Element>(v: &mut vector<Element>, e: Element);

Pop an element from the end of the vector v in-place and return the owned value. Will abort if v is empty.

从向量 v 的末尾就地弹出一个元素并返回拥有的值。如果 v 为空,将中止。

    native public fun pop_back<Element>(v: &mut vector<Element>): Element;

Remove the element at index i in the vector v and return the owned value that was previously stored at i in v. All elements occurring at indices greater than i will be shifted down by 1. Will abort if i is out of bounds for v.

删除向量 v 中索引 i 处的元素,并返回先前存储在 v 中 i 处的拥有值。所有出现在索引处大于 i 的元素将向下移动 1。如果 i 超出 v 的范围,将中止。

    public fun remove<Element>(v: &mut vector<Element>, i: u64): Element;

Swap the ith element of the vector v with the last element and then pop this element off of the back of the vector and return the owned value that was previously stored at index i. This operation is O(1), but does not preserve ordering of elements in the vector. Aborts if the index i is out of bounds for the vector v.

将向量 v 的第 i 个元素与最后一个元素交换,然后将该元素从向量的背面弹出,并返回之前存储在索引 i 处的拥有值。此操作为 O(1),但不保留向量中元素的顺序。如果索引 i 超出向量 v 的范围,则中止。

    public fun swap_remove<Element>(v: &mut vector<Element>, i: u64): Element;

Swap the elements at the i'th and j'th indices in the vector v. Will abort if either of i or j are out of bounds for v.

交换向量 v 中第 i 个和第 j 个索引处的元素。如果 i 或 j 中的任何一个超出 v 的范围,则将中止。

    native public fun swap<Element>(v: &mut vector<Element>, i: u64, j: u64);

Reverse the order of the elements in the vector v in-place.

就地反转向量 v 中元素的顺序。

    public fun reverse<Element>(v: &mut vector<Element>);

Return the index of the first occurrence of an element in v that is equal to e. Returns (true, index) if such an element was found, and (false, 0) otherwise.

返回 v 中等于 e 的元素第一次出现的索引。如果找到这样的元素,则返回 (true, index),否则返回 (false, 0)。

    public fun index_of<Element>(v: &vector<Element>, e: &Element): (bool, u64);

Return if an element equal to e exists in the vector v.

如果向量 v 中存在等于 e 的元素,则返回。

    public fun contains<Element>(v: &vector<Element>, e: &Element): bool;

Return the length of a vector.

返回向量的长度。

    native public fun length<Element>(v: &vector<Element>): u64;

Return whether the vector v is empty.

返回向量 v 是否为空。

    public fun is_empty<Element>(v: &vector<Element>): bool;

option

The option module defines a generic option type Option<T> that represents a value of type T that may, or may not, be present. It is published under the named address Std.

The Move option type is internally represented as a singleton vector, and may contain a value of resource or copyable kind. If you are familiar with option types in other languages, the Move Option behaves similarly to those with a couple notable exceptions since the option can contain a value of kind resource. Particularly, certain operations such as get_with_default and destroy_with_default require that the element type T be of copyable kind.

The API for the option module is as as follows

选项

选项模块定义了一个通用选项类型 Option T,它代表一个类型 T 的值,该值可能存在,也可能不存在。它以命名地址 Std 发布。

Move 选项类型在内部表示为单例向量,并且可能包含资源或可复制种类的值。如果您熟悉其他语言中的选项类型,则移动选项的行为类似于那些具有几个值得注意的例外的选项,因为该选项可以包含 kind 资源的值。特别是,某些操作,如 get_with_default 和 destroy_with_default 要求元素类型 T 是可复制类型。

选件模块的 API 如下

Types

Generic type abstraction of a value that may, or may not, be present. Can contain a value of either resource or copyable kind.

类型

可能存在或不存在的值的通用类型抽象。可以包含资源或可复制类型的值。

    struct Option<T>;

Functions

Create an empty Option of that can contain a value of Element type.

功能

创建一个可以包含元素类型值的空选项。

    public fun none<Element>(): Option<Element>;

Create a non-empty Option type containing a value e of type Element.

创建一个包含 Element 类型的值 e 的非空 Option 类型。

    public fun some<Element>(e: T): Option<Element>;

Return an immutable reference to the value inside the option opt_elem Will abort if opt_elem does not contain a value.

返回对选项 opt_elem 中值的不可变引用 如果 opt_elem 不包含值,将中止。

    public fun borrow<Element>(opt_elem: &Option<Element>): &Element;

Return a reference to the value inside opt_elem if it contains one. If opt_elem does not contain a value the passed in default_ref reference will be returned. Does not abort.

如果它包含一个,则返回对 opt_elem 内的值的引用。如果 opt_elem 不包含值,则将返回传入的 default_ref 引用。不中止。

    public fun borrow_with_default<Element>(opt_elem: &Option<Element>, default_ref: &Element): &Element;

Return a mutable reference to the value inside opt_elem. Will abort if opt_elem does not contain a value.

返回对 opt_elem 中值的可变引用。如果 opt_elem 不包含值,将中止。

    public fun borrow_mut<Element>(opt_elem: &mut Option<Element>): &mut Element;

Convert an option value that contains a value to one that is empty in-place by removing and returning the value stored inside opt_elem. Will abort if opt_elem does not contain a value.

通过删除并返回存储在 opt_elem 中的值,将包含值的选项值转换为就地为空的值。如果 opt_elem 不包含值,将中止。

    public fun extract<Element>(opt_elem: &mut Option<Element>): Element;

Return the value contained inside the option opt_elem if it contains one. Will return the passed in default value if opt_elem does not contain a value. The Element type that the Option type is instantiated with must be of copyable kind in order for this function to be callable.

如果它包含一个,则返回选项 opt_elem 中包含的值。如果 opt_elem 不包含值,将返回传入的默认值。用于实例化 Option 类型的 Element 类型必须是可复制类型,才能使此函数可调用。

    public fun get_with_default<Element: copyable>(opt_elem: &Option<Element>, default: Element): Element;

Convert an empty option opt_elem to an option value that contains the value e. Will abort if opt_elem already contains a value.

将空选项 opt_elem 转换为包含值 e 的选项值。如果 opt_elem 已经包含一个值,将中止。

    public fun fill<Element>(opt_elem: &mut Option<Element>, e: Element);

Swap the value currently contained in opt_elem with new_elem and return the previously contained value. Will abort if opt_elem does not contain a value.

将 opt_elem 中当前包含的值交换为 new_elem 并返回先前包含的值。如果 opt_elem 不包含值,将中止。

    public fun swap<Element>(opt_elem: &mut Option<Element>, e: Element): Element;

Return true if opt_elem contains a value equal to the value of e_ref. Otherwise, false will be returned.

如果 opt_elem 包含的值等于 e_ref 的值,则返回 true。否则,将返回 false。

    public fun contains<Element>(opt_elem: &Option<Element>, e_ref: &Element): bool;

Return true if opt_elem does not contain a value.

如果 opt_elem 不包含值,则返回 true。

    public fun is_none<Element>(opt_elem: &Option<Element>): bool;

Return true if opt_elem contains a value.

如果 opt_elem 包含一个值,则返回 true。

    public fun is_some<Element>(opt_elem: &Option<Element>): bool;

Unpack opt_elem and return the value that it contained. Will abort if opt_elem does not contain a value.

解包 opt_elem 并返回它包含的值。如果 opt_elem 不包含值,将中止。

    public fun destroy_some<Element>(opt_elem: Option<Element>): Element;

Destroys the opt_elem value passed in. If opt_elem contained a value it will be returned otherwise, the passed in default value will be returned.

销毁传入的 opt_elem 值。如果 opt_elem 包含值,则返回,否则返回传入的默认值。

    public fun destroy_with_default<Element: copyable>(opt_elem: Option<Element>, default: Element): Element;

Destroys the opt_elem value passed in, opt_elem must be empty and not contain a value. Will abort if opt_elem contains a value.

销毁传入的 opt_elem 值,opt_elem 必须为空且不包含值。如果 opt_elem 包含一个值,将中止。

    public fun destroy_none<Element>(opt_elem: Option<Element>);

errors

Recall that each abort code in Move is represented as an unsigned 64-bit integer. The errors module defines a common interface that can be used to "tag" each of these abort codes so that they can represent both the error category along with an error reason.

Error categories are declared as constants in the errors module and are globally unique with respect to this module. Error reasons on the other hand are module-specific error codes, and can provide greater detail (perhaps, even a particular reason) about the specific error condition. This representation of a category and reason for each error code is done by dividing the abort code into two sections.

The lower 8 bits of the abort code hold the error category. The remaining 56 bits of the abort code hold the error reason. The reason should be a unique number relative to the module which raised the error and can be used to obtain more information about the error at hand. It should mostly be used for diagnostic purposes as error reasons may change over time if the module is updated.

错误

回想一下,Move 中的每个中止代码都表示为一个无符号的 64 位整数。 errors 模块定义了一个通用接口,可用于“标记”每个中止代码,以便它们可以表示错误类别和错误原因。

错误类别在错误模块中被声明为常量,并且相对于该模块是全局唯一的。另一方面,错误原因是特定于模块的错误代码,可以提供有关特定错误条件的更多详细信息(甚至可能是特定原因)。每个错误代码的类别和原因的这种表示是通过将中止代码分为两部分来完成的。

中止代码的低 8 位保存错误类别。中止代码的剩余 56 位保存错误原因。原因应该是相对于引发错误的模块的唯一编号,并且可用于获取有关手头错误的更多信息。它应该主要用于诊断目的,因为如果更新模块,错误原因可能会随着时间而改变。

CategoryReason
8 bits56 bits

Since error categories are globally stable, these present the most stable API and should in general be what is used by clients to determine the messages they may present to users (whereas the reason is useful for diagnostic purposes). There are public functions in the errors module for creating an abort code of each error category with a specific reason number (represented as a u64).

由于错误类别是全局稳定的,因此它们提供了最稳定的 API,通常应该是客户端用来确定它们可能呈现给用户的消息的内容(而原因对于诊断目的很有用)。错误模块中有公共函数,用于为每个错误类别创建一个带有特定原因号的中止代码(表示为 u64)。

Constants

The system is in a state where the performed operation is not allowed.

常数

系统处于不允许执行的操作的状态。

    const INVALID_STATE: u8 = 1;

A specific account address was required to perform an operation, but a different address from what was expected was encounterd.

执行操作需要特定的帐户地址,但遇到了与预期不同的地址。

    const REQUIRES_ADDRESS: u8 = 2;

An account did not have the expected role for this operation. Useful for Role Based Access Control (RBAC) error conditions.

帐户没有此操作的预期角色。对于基于角色的访问控制 (RBAC) 错误情况很有用。

    const REQUIRES_ROLE: u8 = 3;

An account did not not have a required capability. Useful for RBAC error conditions.

帐户没有所需的功能。对于 RBAC 错误情况很有用。

    const REQUIRES_CAPABILITY: u8 = 4;

A resource was expected, but did not exist under an address.

应有资源,但地址下不存在。

    const NOT_PUBLISHED: u8 = 5;

Attempted to publish a resource under an address where one was already published.

尝试在已发布资源的地址下发布资源。

    const ALREADY_PUBLISHED: u8 = 6;

An argument provided for an operation was invalid.

为操作提供的参数无效。

    const INVALID_ARGUMENT: u8 = 7;

A limit on a value was exceeded.

超出了某个值的限制。

    const LIMIT_EXCEEDED: u8 = 8;

An internal error (bug) has occurred.

发生内部错误(错误)。

    const INTERNAL: u8 = 10;

A custom error category for extension points.

扩展点的自定义错误类别。

    const CUSTOM: u8 = 255;

Functions

Should be used in the case where invalid (global) state is encountered. Constructs an abort code with specified reason and category INVALID_STATE. Will abort if reason does not fit in 56 bits.

函数

应该在遇到无效(全局)状态的情况下使用。构造具有指定原因和类别 INVALID_STATE 的中止代码。如果原因不适合 56 位,将中止。

    public fun invalid_state(reason: u64): u64;

Should be used if an account's address does not match a specific address. Constructs an abort code with specified reason and category REQUIRES_ADDRESS. Will abort if reason does not fit in 56 bits.

如果帐户的地址与特定地址不匹配,则应使用。构造具有指定原因和类别 REQUIRES_ADDRESS 的中止代码。如果原因不适合 56 位,将中止。

    public fun requires_address(reason: u64): u64;

Should be used if a role did not match a required role when using RBAC. Constructs an abort code with specified reason and category REQUIRES_ROLE. Will abort if reason does not fit in 56 bits.

如果在使用 RBAC 时角色与所需角色不匹配,则应使用该角色。构造具有指定原因和类别 REQUIRES_ROLE 的中止代码。如果原因不适合 56 位,将中止。

    public fun requires_role(reason: u64): u64;

Should be used if an account did not have a required capability when using RBAC. Constructs an abort code with specified reason and category REQUIRES_CAPABILITY. Should be Will abort if reason does not fit in 56 bits.

如果帐户在使用 RBAC 时没有所需的功能,则应使用。构造具有指定原因和类别 REQUIRES_CAPABILITY 的中止代码。如果原因不适合 56 位,则应该是将中止。

    public fun requires_capability(reason: u64): u64;

Should be used if a resource did not exist where one was expected. Constructs an abort code with specified reason and category NOT_PUBLISHED. Will abort if reason does not fit in 56 bits.

如果资源在预期的地方不存在,则应使用该资源。构造具有指定原因和类别 NOT_PUBLISHED 的中止代码。如果原因不适合 56 位,将中止。

    public fun not_published(reason: u64): u64;

Should be used if a resource already existed where one was about to be published. Constructs an abort code with specified reason and category ALREADY_PUBLISHED. Will abort if reason does not fit in 56 bits.

如果资源已经存在且即将发布,则应使用该资源。构造一个具有指定原因和类别 ALREADY_PUBLISHED 的中止代码。如果原因不适合 56 位,将中止。

    public fun already_published(reason: u64): u64;

Should be used if an invalid argument was passed to a function/operation. Constructs an abort code with specified reason and category INVALID_ARGUMENT. Will abort if reason does not fit in 56 bits.

如果将无效参数传递给函数/操作,则应使用。构造具有指定原因和类别 INVALID_ARGUMENT 的中止代码。如果原因不适合 56 位,将中止。

    public fun invalid_argument(reason: u64): u64;

Should be used if a limit on a specific value is reached, e.g., subtracting 1 from a value of 0. Constructs an abort code with specified reason and category LIMIT_EXCEEDED. Will abort if reason does not fit in 56 bits.

如果达到特定值的限制,则应使用,例如,从 0 中减去 1。构造具有指定原因和类别 LIMIT_EXCEEDED 的中止代码。如果原因不适合 56 位,将中止。

    public fun limit_exceeded(reason: u64): u64;

Should be used if an internal error or bug was encountered. Constructs an abort code with specified reason and category INTERNAL. Will abort if reason does not fit in 56 bits.

如果遇到内部错误或错误,应使用。构造具有指定原因和类别 INTERNAL 的中止代码。如果原因不适合 56 位,将中止。

    public fun internal(reason: u64): u64;

Used for extension points, should be not used under most circumstances. Constructs an abort code with specified reason and category CUSTOM. Will abort if reason does not fit in 56 bits.

用于扩展点,在大多数情况下不应该使用。构造具有指定原因和类别 CUSTOM 的中止代码。如果原因不适合 56 位,将中止。

    public fun custom(reason: u64): u64;

fixed_point32

The fixed_point32 module defines a fixed-point numeric type with 32 integer bits and 32 fractional bits. Internally, this is represented as a u64 integer wrapped in a struct to make a unique fixed_point32 type. Since the numeric representation is a binary one, some decimal values may not be exactly representable, but it provides more than 9 decimal digits of precision both before and after the decimal point (18 digits total). For comparison, double precision floating-point has less than 16 decimal digits of precision, so you should be careful about using floating-point to convert these values to decimal.

固定点32

fixed_point32 模块定义了一个具有 32 个整数位和 32 个小数位的定点数值类型。在内部,这表示为一个包裹在结构中的 u64 整数,以形成唯一的 fixed_point32 类型。由于数字表示是二进制的,因此某些十进制值可能无法精确表示,但它在小数点前后都提供了超过 9 位的精度(总共 18 位)。作为比较,双精度浮点的精度小于 16 位小数,因此在使用浮点将这些值转换为十进制时应小心。

Types

Represents a fixed-point numeric number with 32 fractional bits.

类型

表示具有 32 个小数位的定点数值。

    struct FixedPoint32;

Functions

Multiply a u64 integer by a fixed-point number, truncating any fractional part of the product. This will abort if the product overflows.

函数

将 u64 整数乘以定点数,截断乘积的任何小数部分。如果产品溢出,这将中止。

    public fun multiply_u64(val: u64, multiplier: FixedPoint32): u64;

Divide a u64 integer by a fixed-point number, truncating any fractional part of the quotient. This will abort if the divisor is zero or if the quotient overflows.

将 u64 整数除以定点数,截断商的任何小数部分。如果除数为零或商溢出,这将中止。

    public fun divide_u64(val: u64, divisor: FixedPoint32): u64;

Create a fixed-point value from a rational number specified by its numerator and denominator. Calling this function should be preferred for using fixed_point32::create_from_raw_value which is also available. This will abort if the denominator is zero. It will also abort if the numerator is nonzero and the ratio is not in the range $2^{-32}\ldots2^{32}-1$. When specifying decimal fractions, be careful about rounding errors: if you round to display $N$ digits after the decimal point, you can use a denominator of $10^N$ to avoid numbers where the very small imprecision in the binary representation could change the rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013.

根据分子和分母指定的有理数创建定点值。使用也可用的 fixed_point32::create_from_raw_value 应该首选调用此函数。如果分母为零,这将中止。如果分子不为零并且比率不在 $2 {-32}ldots2 {32}-1$ 范围内,它也会中止。指定小数时,请注意舍入错误:如果四舍五入以显示小数点后的 $N$ 个数字,则可以使用分母 $10 N$ 来避免二进制表示中非常小的不精确性可能会改变四舍五入,例如,0.0125 将向下舍入为 0.012,而不是向上舍入为 0.013。

    public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32;

Create a fixedpoint value from a raw u64 value.

从原始 u64 值创建定点值。

    public fun create_from_raw_value(value: u64): FixedPoint32;

Returns true if the decimal value of num is equal to zero.

如果 num 的十进制值等于 0,则返回 true。

    public fun is_zero(num: FixedPoint32): bool;

Accessor for the raw u64 value. Other less common operations, such as adding or subtracting FixedPoint32 values, can be done using the raw values directly.

原始 u64 值的访问器。其他不太常见的操作,例如添加或减去 FixedPoint32 值,可以直接使用原始值完成。

    public fun get_raw_value(num: FixedPoint32): u64;

Move 编码约定

本节列出了 Move 团队认为有用的一些基本的 Move 编码约定。这些只是建议,如果你喜欢其他格式指南和约定,你可以随时使用它们。

命名

  • 模块名称:应该使用小写的蛇形命名法,例如:fixed_point32、vector。
  • 类型名称:如果不是原生数据类型,则应使用驼峰命名法,例如:Coin、RoleId。
  • 函数名称:应该使用小写的蛇形命名法,例如:destroy_empty。
  • 常量名称:应该使用大写的蛇形命名法,例如:REQUIRES_CAPABILITY。
  • 泛型类型应该具备描述性,当然在适当的情况下也可以是反描述性的,例如:Vector 泛型类型的参数可以是 T 或 Element。大多数情况下,模块中的“主”类型命名应该与模块名相同,例如:option::Option,fixed_point32::FixedPoint32。
  • 模块文件名称:应该与模块名相同,例如:Option.move。
  • 脚本文件名称:应该使用小写的蛇形命名法,并且应该与脚本中的“主”函数名匹配。
  • 混合文件名称:如果文件包含多个模块和/或脚本,文件命名应该使用小写的蛇形命名法,并且不需要与内部的任何特定模块/脚本名匹配。

导入

  • 所有模块的 use 语句都应该位于模块的顶部。
  • 函数应该从声明它们的模块中完全限定地导入和使用, 而不是在顶部导入。
  • 类型应该在顶部导入。如果存在名称冲突,应使用 as 在本地适当地重命名类型。

例如,如果有一个模块:

module 0x1::foo {
    struct Foo { }
    const CONST_FOO: u64 = 0;
    public fun do_foo(): Foo { Foo{} }
    ...
}

此时将被导入并使用:

module 0x1::bar {
    use 0x1::foo::{Self, Foo};

    public fun do_bar(x: u64): Foo {
        if (x == 10) {
            foo::do_foo()
        } else {
            abort 0
        }
    }
    ...
}

并且,如果在导入两个模块时存在本地名称冲突:

module other_foo {
    struct Foo {}
    ...
}

module 0x1::importer {
    use 0x1::other_foo::Foo as OtherFoo;
    use 0x1::foo::Foo;
    ...
}

注释

  • 每个模块、结构体和公共函数声明都应该有对应的注释。
  • Move 有文档注释 ///,常规单行注释 //,块注释 /* */,和块文档注释 /** */。

格式化

Move 团队计划编写一个自动格式化程序来执行格式化约定。然而,在此期间:

  • 除 script 和 address 块外,其他的内容应使用四个空格的缩进。
  • 每行代码,如果超过 100 个字符,应该换行。
  • 结构体和常量应该在模块中的所有函数之前声明。