Move —— Ability 介绍和 drop

Move 语言通过 Ability 系统来控制类型的行为能力,这是保障资产安全的核心机制。本文介绍 Ability 的概念、四种能力类型,并重点讲解 drop 能力的作用——它决定了一个值是否可以在作用域结束时被自动丢弃。

1. 什么是 Ability?

在 Move 中,结构体(Struct)默认是没有任何能力的。这意味着它们不能被复制、不能被丢弃,也不能被存储。

通过 has 关键字,我们可以赋予结构体以下四种能力:

  1. drop:允许值被丢弃。
  2. copy:允许值被复制。
  3. store:允许值被存储在全局状态中。
  4. key:允许值作为全局存储中的对象。

2. drop 能力

Move 的类型系统非常严格。如果一个结构体没有 drop 能力,创建它之后就必须将它转移(传递给其他函数)或显式销毁(解构)。如果试图忽略它(例如函数结束时不返回它),编译器会报错。

2.1 没有 drop 的情况(报错示例)

1
2
3
4
5
6
7
8
9
10
11
public fun get_student(student: Student): (u8, bool, u64, u64) {
let age = student.age;
let isMale = student.isMale;
let literature = student.grades.literature;
let math = student.grades.math;
// let Student { age, isMale, grades: Grades { literature, math } } = student;

// 编译错误:
// The type 'temp_test::temp_test::Student' does not have the ability 'drop'
(age, isMale, literature, math)
}

2.2 添加 drop 能力

赋予 drop 能力后,结构体就可以像普通变量一样,在作用域结束时自动被清理,或者通过 _ 忽略。

1
2
3
4
5
6
7
8
9
10
// 使用 `has` 关键字添加能力
public struct Student has drop {
age: u8,
isMale: bool,
grades: Grades,
}
public struct Grades has drop {
literature: u64,
math: u64,
}

2.3 为什么基本类型不需要加 drop

你可能会发现 u8, bool 等基本类型不需要手动写 has drop。 这是因为 Move 的原生基本类型(Primitive Types)(如 u8, u64, bool, address)默认已经包含了 dropcopystore 能力。