502-move数据类型
0x-wen

基础类型

变量

1
2
3
4
5
6
7
8
// 格式如下:
let <variable_name>[: <type>] = <expression>;
let mut <variable_name>[: <type>] = <expression>;

let x: bool = true;
let mut y: u8 = 42;
y = 43;
let x: u8 = 42; // shadowed

布尔值

1
2
3
// 无需显式指定类型 - 编译器可以从值中推断出类型
let x = true;
let y = false;

整数类型

1
2
3
4
5
6
7
8
let x: u8 = 42;
let y: u16 = 42;
// ...
let z: u256 = 42;

// Both are equivalent
let x: u8 = 42;
let x = 42u8;

整数溢出

1
2
3
4
5
6
7
8
let x: u8 = 255;
let y: u8 = 255;
let z: u16 = (x as u16) + ((y as u16) * 2);

let x = 255u8;
let y = 1u8;
// This will raise an error
let z = x + y;

运算符

1
2
// 加法、减法、乘法、除法和余数
// + | - | * | / | %

地址类型

1
2
3
4
5
6
7
8
9
// address 类型。它是一个 32 字节的值,可用于表示区块链上的任何地址。
// 地址以两种语法形式使用:前缀为 0x 的十六进制地址和命名地址。

// address literal
let value: address = @0x1;

// named address registered in Move.toml
let value = @std;
let other = @sui;

地址文字以 @ 符号开头,后跟十六进制数字或标识符。十六进制数被解释为 32 字节值。

地址转换

由于地址类型是 32 字节值,因此可以将其转换为 u256 类型,反之亦然。它还可以与 vector<u8> 类型相互转换。

  • 示例:将地址转换为 u256 类型并返回。
1
2
3
4
use sui::address;

let addr_as_u256: u256 = address::to_u256(@0x1);
let addr = address::from_u256(addr_as_u256);
  • 示例:将地址转换为 vector<u8> 类型并返回。
1
2
3
4
use sui::address;

let addr_as_u8: vector<u8> = address::to_bytes(@0x1);
let addr = address::from_bytes(addr_as_u8);
  • 示例:将地址转换为字符串。
1
2
3
4
use sui::address;
use std::string::String;

let addr_as_string: String = address::to_string(@0x1);

语句与表达式

最后一行是表达式将用于赋值,是语句将返回一个默认单元类型 ()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// block with an empty expression, however, the compiler will
// insert an empty expression automatically: `let none = { () }`
// let none = {};

// block with let statements and an expression.
let sum = {
let a = 1;
let b = 2;
a + b // last expression is the value of the block
};

// block is an expression, so it can be used in an expression and
// doesn't have to be assigned to a variable.
{
let a = 1;
let b = 2;
a + b; // not returned - semicolon.
// compiler automatically inserts an empty expression `()`
};

结构体

数据合集,用什么来表示长方形的长和宽。Move 不支持递归结构,这意味着结构不能将自身包含为字段。

1
2
3
4
public struct Artist {
name: String,
age: u8,
}

函数调用

add 的返回值是一个表达式 a+b,返回类型是u8

1
2
3
4
5
6
7
8
fun add(a: u8, b: u8): u8 {
a + b
}

#[test]
fun some_other() {
let sum = add(1, 2); // add(1, 2) is an expression with type u8
}

流程控制

它们也是表达式,因此它们返回一个值。

1
2
3
4
5
6
7
8
9
// if is an expression, so it returns a value; if there are 2 branches,
// the types of the branches must match.
if (bool_expr) expr1 else expr2;

// while is an expression, but it returns `()`.
while (bool_expr) { expr; };

// loop is an expression, but returns `()` as well.
loop { expr; break };
由 Hexo 驱动 & 主题 Keep
总字数 42.8k