Move —— 数据类型

Move 是一门强类型语言,所有变量在编译时都必须有明确的类型。本文介绍 Move 的三种原生数据类型:布尔类型(Boolean)、无符号整数类型(Unsigned Integer)和地址类型(Address),以及它们的使用方式和注意事项。

1. 布尔类型(Boolean Type)

布尔值有两个可能的值:truefalse,大小为 1 个字节。

1
2
3
4
public fun main() {
let t = true;
let f: bool = false; // 显式类型标注
}

2. 整数类型(Integer)

Move 只支持无符号整数。

Type(Unsigned) Length Value Range
u8 8-bit 0 to 255
u16 16-bit 0 to 65,535
u32 32-bit 0 to 2^32-1
u64 64-bit 0 to 2^64-1
u128 128-bit 0 to 2^128-1
u256 256-bit 0 to 2256 - 1

注意:

  • 如果未提供显式类型,则默认类型为 u64
  • 如果声明变量的值超过数据类型的范围(例如 let x: u8 = 256;),Move 会在编译时报错。如果在运行时发生算术溢出(例如 let x: u8 = 255; let y = x + 1;),程序会立即中止 (Abort)。这是 Move 保证安全性的核心特性,它不允许整数溢出(或下溢)。

3. 地址类型(Address)

  • address 类型用于表示账户地址或对象 ID。
  • 地址是 32 字节(256 位)的值。
  • 可以用 @ 符号创建地址字面量。
1
2
let addr: address = @0x1;		// 0x00000000000000000000000000000001 的缩写
let sender = @0x42; // 0x00000000000000000000000000000042 的缩写