4.2 内置类型(Built-in Types)

Every value in Sway is of a certain type. Although deep down, all values are just ones and zeroes in the underlying virtual machine, Sway needs to know what those ones and zeroes actually mean. This is accomplished with types.

Sway中的每个值都有一定的类型。虽然在底层,所有的值在虚拟机中都只是1和0,但Sway需要知道这些1和0的实际含义。这是通过 types 完成的。

Sway is a statically typed language. At compile time, the types of every value must be known. This does not mean you need to specify every single type: usually, the type can be reasonably inferred by the compiler.

Sway是一种静态类型的语言。在编译时,每个值的类型都必须是已知的。这并不意味着你需要指定每一种类型:通常,编译器可以合理地推断出类型。

原始类型 (Primitive Types)

Sway has the following primitive types: Sway有以下原始类型:

  1. u8 (8-bit unsigned integer) u8 (8位无符号整数)

  2. u16 (16-bit unsigned integer) u16 (16位无符号整数)

  3. u32 (32-bit unsigned integer) u32 (32位无符号整数)

  4. u64 (64-bit unsigned integer) u64 (64位无符号整数)

  5. str[] (fixed-length string) str[] (固定长度的字符串)

  6. bool (Boolean true or false) bool(布尔值truefalse

  7. b256 (256 bits (32 bytes), i.e. a hash) b256` (256位(32字节),即一个哈希值)

All other types in Sway are built up of these primitive types, or references to these primitive types. You may notice that there are no signed integers—this is by design. In the blockchain domain that Sway occupies, floating-point values and negative numbers have smaller utility, so their implementation has been left up to libraries for specific use cases.

Sway中的所有其他类型都是由这些原始类型,或对这些原始类型的引用建立起来的。你可能会注意到,没有带符号的整数--这是设计上刻意的。在Sway所处的区块链领域,浮点值和负数的效用较小,所以它们的实现被留给了特定用例的库。

数值类型 (Numeric Types)

All of the unsigned integer types are numeric types.

所有的无符号整数类型都是数值类型。

Numbers can be declared with binary syntax, hexadecimal syntax, base-10 syntax, and underscores for delineation. Let's take a look at the following valid numeric primitives:

数字可以用二进制语法、十六进制语法、十进制语法和下划线来声明。让我们来看看下面这些有效的数字基元:

0xffffff    // hexadecimal
0b10101010  // binary
10          // base-10
100_000     // underscore delineated base-10
0x1111_0000 // underscore delineated binary
0xfff_aaa   // underscore delineated hexadecimal

The default numeric type is u64. The FuelVM's word size is 64 bits, and the cases where using a smaller numeric type saves space are minimal.

默认的数字类型是u64。FuelVM的字大小是64位,使用较小数字类型且可以节省空间的情况很少。

布尔类型 (Boolean Type)

The boolean type (bool) has two potential values: true or false. Boolean values are typically used for conditional logic or validation, for example in if expressions. Booleans can be negated, or flipped, with the unary negation operator !. For example:

布尔类型(bool)有两个潜在的值: truefalse。布尔值通常用于条件逻辑或验证,例如在if表达式中。布尔值可以被否定,或用单数否定操作符翻转,例如:

fn returns_false() -> bool {
    let boolean_value: bool = true;
    !boolean_value
}

字符串类型 (String Type)

In Sway, static-length strings are a primitive type. This means that when you declare a string, its size is a part of its type. This is necessary for the compiler to know how much memory to give for the storage of that data. The size of the string is denoted with square brackets. Let's take a look:

在Sway中,静态长度的字符串是一种原始类型。这意味着,当你声明一个字符串时,它的大小是其类型的一部分。这对编译器来说是必要的,因为它知道要给多少内存来存储该数据。字符串的大小是用方括号表示的。让我们看一下:

let my_string: str[4] = "fuel";

Because the string literal "fuel" is four letters, the type is str[4], denoting a static length of 4 characters. Strings default to UTF-8 in Sway.

因为字符串字面意思"fuel"是四个字母,类型是str[4],表示静态长度为4个字符。字符串在Sway中默认为UTF-8。

复合类型 (Compound Types)

Compound types are types that group multiple values into one type. In Sway, we have arrays and tuples.

复合类型 是将多个值组合成一个类型的类型。在Sway中,我们有数组和元组。

元组类型(Tuple Types)

A tuple is a general-purpose static-length aggregation of types. In more plain terms, a tuple is a single type that consists of an aggregate of zero or more types. The internal types that make up a tuple, and the tuple's arity, define the tuple's type. Let's take a look at some examples.

元组是一种通用的静态长度的聚合类型。用更通俗的话来说,元组是一个由零个或多个类型的集合,组成的单一类型。组成一个元组的内部类型和元组的算术,定义了元组的类型。让我们看一下一些例子。

let x: (u64, u64) = (0, 0);

This is a tuple, denoted by parenthesized, comma-separated values. Note that the type annotation, (u64, u64), is similar in syntax to the expression which instantiates that type, (0, 0).

这是一个元组,由括号内的逗号分隔的值表示。注意类型注释(u64, u64),与实例化该类型的表达式(0, 0)在语法上相似。

let x: (u64, bool) = (42, true);
assert(x.1);

In this example, we have created a new tuple type, (u64, bool), which is a composite of a u64 and a bool. To access a value within a tuple, we use tuple indexing: x.1 stands for the first (zero-indexed, so the bool) value of the tuple. Likewise, x.0 would be the zeroth, u64 value of the tuple. Tuple values can also be accessed via destructuring:

在这个例子中,我们创建了一个新的元组类型,(u64, bool),它是一个u64和一个bool的组合。为了访问元组中的一个值,我们使用 元组索引x.1代表元组的第一个(零索引,所以是bool)值。同样的, x.0是元组的第2个, u64值. 元组的值也可以通过去结构化来访问:

struct Foo {}
let x: (u64, Foo, bool) = (42, Foo {}, true);
let (number, foo, boolean) = x;

To create one-arity tuples, we will need to add a trailing comma:

为了创建单数图元组,我们需要在尾部添加一个逗号:

let x: u64 = (42);     // x is of type u64
let y: (u64) = (42);   // y is of type u64
let z: (u64,) = (42,); // z is of type (u64), i.e. a one-arity tuple
let w: (u64) = (42,);  // type error

数组 (Arrays)

An array is similar to a tuple, but an array's values must all be of the same type. Arrays can hold arbitrary types including non-primitive types.

数组类似于元组,但数组的值必须都是同一类型。数组可以容纳任意的类型,包括非基本类型。

An array is written as a comma-separated list inside square brackets:

一个数组被写成方括号内的逗号分隔的列表:

let x = [1, 2, 3, 4, 5];

Arrays are allocated on the stack since their size is known. An array's size is always static, i.e. it cannot change. An array of five elements cannot become an array of six elements.

数组是在堆栈中分配的,因为它们的大小是已知的。数组的大小永远是静态的,也就是说,它不能改变。一个5个元素的数组不能变成一个6个元素的数组。

Arrays can be iterated over, unlike tuples. An array's type is written as the type the array contains followed by the number of elements, semicolon-separated and within square brackets, e.g. [u64; 5]. To access an element in an array, use the array indexing syntax, i.e. square brackets.

数组可以被迭代,与图元不同。一个数组的类型被写成数组包含的类型,然后是元素的数量,用分号隔开,放在方括号内,例如:[u64; 5]。要访问一个数组中的元素,请使用 数组索引语法,即方括号。

Array elements can also be mutated if the underlying array is declared as mutable:

如果底层数组被声明为可改变的,数组元素也可以被改变:

let mut x = [1, 2, 3, 4, 5];
x[0] = 0;
script;

struct Foo {
    f1: u32,
    f2: b256,
}

fn main() {
    // Array of integers with type ascription
    let array_of_integers: [u8; 5] = [1, 2, 3, 4, 5];

    // Array of strings
    let array_of_strings = ["Bob", "Jan", "Ron"];

    // Array of structs
    let array_of_structs: [Foo; 2] = [
        Foo {
            f1: 11,
            f2: 0x1111111111111111111111111111111111111111111111111111111111111111,
        },
        Foo {
            f1: 22,
            f2: 0x2222222222222222222222222222222222222222222222222222222222222222,
        },
    ];

    // Accessing an element of an array
    let mut array_of_bools: [bool; 2] = [true, false];
    assert(array_of_bools[0]);

    // Mutating the element of an array
    array_of_bools[1] = true;
    assert(array_of_bools[1]);
}

Last updated