6.1 高级类型 (Advanced Types)

用类型别名创建类型同义词 (Creating Type Synonyms with Type Aliases)

Sway provides the ability to declare a type alias to give an existing type another name. For this we use the type keyword. For example, we can create the alias Kilometers to u64 like so:

Sway提供了声明一个类型别名的能力,进而给现有的类型另一个名字。为此我们使用type关键字。例如,我们可以创建Kilometersu64的别名,像这样:

type Kilometers = u64;

Now, the alias Kilometers is a synonym for u64. Note that Kilometers is not a separate new type. Values that have the type Kilometers will be treated the same as values of type u64:

现在,别名 Kilometersu64的 _同义词。请注意,Kilometers不是 **一个独立的新类型 **。具有 Kilometers类型的值将被视为与 u64类型的值相同:

    let x: u64 = 5;
    let y: Kilometers = 5;
    assert(x + y == 10);

Because Kilometers and u64 are the same type, we can add values of both types and we can pass Kilometers values to functions that take u64 parameters. However, using this method, we don’t get the type checking benefits that we get from introducing a separate new type called Kilometers. In other words, if we mix up Kilometers and i32 values somewhere, the compiler will not give us an error.

因为Kilometersu64是同一类型,我们就可以添加两种类型的值,我们可以将Kilometers的值传递给接受u64参数的函数。然而,使用这种方法,我们无法得到类型检查的好处,因为我们引入了一个名为 Kilometers独立的 新类型。换句话说,如果我们把Kilometersi32的值混在一起,编译器不会给我们一个错误。

The main use case for type synonyms is to reduce repetition. For example, we might have a lengthy array type like this:

类型同义词的主要使用情况是减少重复。例如,我们可能有一个很长的数组类型,像这样:

[MyStruct<u64, b256>; 5]

Writing this lengthy type in function signatures and as type annotations all over the code can be tiresome and error prone. Imagine having a project full of code like this:

将这种冗长的类型写在函数签名中,并作为类型注释在代码中随处可见,会让人感到厌烦和容易出错。想象一下,有一个项目充满了这样的代码:

fn foo_long(array: [MyStruct<u64, b256>; 5]) -> [MyStruct<u64, b256>; 5] {
    array
}

A type alias makes this code more manageable by reducing the repetition. Below, we’ve introduced an alias named MyArray for the verbose type and can replace all uses of the type with the shorter alias MyArray:

类型别名通过减少重复而使这段代码更容易管理。下面,我们为冗长的类型引入了一个名为MyArray的别名,可以用更短的别名MyArray来代替该类型的所有应用:

fn foo_long(array: [MyStruct<u64, b256>; 5]) -> [MyStruct<u64, b256>; 5] {
    array
}

This code is much easier to read and write! Choosing a meaningful name for a type alias can help communicate your intent as well.

这段代码读起来和写起来都容易多了! 为类型别名选择一个有意义的名字,也有助于传达你的意图。

Last updated