Defining Structs
We can define a struct in Rust with syntax like this:
As with tuples, structs can contain fields of different types. The difference is, a struct defines a named type.
We can create an instance of this struct like this:
Fields can be accessed or set using a dot notation:
If you want to set fields, the entire struct variable (person1
) has to be declared with mut
. It’s not possible to only declare individual fields to be mutable.
If you want to print the struct in one go, you have to enable debug mode with an annotation:
Then we can do the following:
And it prints out nicely.
Passing Structs to Functions
We can pass structs to functions via immutable references. Given the following function:
We can now do this:
Struct Update Syntax
We can create a struct by pre-filling some or all of the fields from another struct.
The ..person1
here must come at the end of the fields we want to change in the new struct instance.
Note that if we were to pre-fill name in this code, the first struct would become invalid, since this would perform a move of the heap-allocated name string to the new struct.
Empty Structs
You can create empty structs.
This prints just Machine
.
Tuple Structs
Tuple structs are structs where the fields aren’t named. The fields can be accessed via the dot notation and indices. Here we define a tuple struct with three floating-point values.
Here’s an example where we access the fields.