Structs and Resources
A struct is a user-defined data structure containing typed fields. Structs can store any non-reference type, including other structs.
We often refer to struct values as resources if they cannot be copied and cannot be dropped. In this case, resource values must have ownership transferred by the end of the function. This property makes resources particularly well served for defining global storage schemas or for representing important values (such as a token).
By default, structs are linear and ephemeral. By this we mean that they: cannot be copied, cannot be dropped, and cannot be stored in global storage. This means that all values have to have ownership transferred (linear) and the values must be dealt with by the end of the program's execution (ephemeral). We can relax this behavior by giving the struct abilities which allow values to be copied or dropped and also to be stored in global storage or to define global storage schemas.
Defining Structs
Structs must be defined inside a module:
address 0x2 {
module m {
struct Foo { x: u64, y: bool }
struct Bar {}
struct Baz { foo: Foo, }
// ^ note: it is fine to have a trailing comma
}
}
Structs cannot be recursive, so the following definition is invalid:
struct Foo { x: Foo }
// ^ error! Foo cannot contain Foo
As mentioned above: by default, a struct declaration is linear and ephemeral. So to allow the value
to be used with certain operations (that copy it, drop it, store it in global storage, or use it as
a storage schema), structs can be granted abilities by annotating them with
has <ability>
:
address 0x2 {
module m {
struct Foo has copy, drop { x: u64, y: bool }
}
}
For more details, see the annotating structs section.
Naming
Structs must start with a capital letter A
to Z
. After the first letter, struct names can
contain underscores _
, letters a
to z
, letters A
to Z
, or digits 0
to 9
.
struct Foo {}
struct BAR {}
struct B_a_z_4_2 {}
This naming restriction of starting with A
to Z
is in place to give room for future language
features. It may or may not be removed later.