10.6 与Rust的不同之处 (Differences From Rust)

Sway shares a lot with Rust, especially its syntax. Because they are so similar, you may be surprised or caught off guard when they differ. This page serves to outline, from a high level, some of the syntactic gotchas that you may encounter.

Sway 与 Rust 有很多共同之处,尤其是它的语法。因其非常相似,所以当它们不同时,您可能会感到惊讶或措手不及。本页旨在从高层次概述您可能遇到的一些语法问题。

穷举的变体语法(Enum Variant Syntax)

In Rust, enums generally take one of three forms: unit variants, which have no inner data, struct variants, which contain named fields, and tuple variants, which contain within them a tuple of data. If you are unfamiliar with these terms, this is what they look like:

在 Rust 中,穷举通常采用三种形式之一:单元变体(没有内部数据)、结构变体(包含命名字段)和元组变体(其中包含数据元组)。如果您不熟悉这些术语,它们如下所示:

// note to those skimming the docs: this is Rust syntax! Not Sway! Don't copy/paste this into a Sway program.

enum Foo {
    UnitVariant,
    TupleVariant(u32, u64, bool),
    StructVariant {
        field_one: bool,
        field_two: bool
    }
}

In Sway, enums are simplified. Enums variants must all specify exactly one type. This type represents their interior data. This is actually isomorphic to what Rust offers, just with a different syntax. I'll now rewrite the above enum but with Sway syntax:

在 Sway 中,穷举得到了简化。穷举变体必须全部指定一种类型。该类型代表它们的内部数据。这实际上与 Rust 提供的同构,只是语法不同。我现在将使用 Sway 语法重写上面的穷举:

// This is equivalent Sway syntax for the above Rust enum.
enum Foo {
    UnitVariant: (),
    TupleVariant: (u32, u64, bool),
    StructVariant: MyStruct,
}

struct MyStruct {
    field_one: bool,
    field_two: bool,
}

Last updated