Structs in Rust
Structs
Structs in Rust are typed collections of fields. They’re useful for grouping data together to form records.
This Person
struct type has name
and age
fields.
new_person
constructs a new Person
struct with the given name.
This syntax creates a new struct.
You can name the fields when initializing a struct.
Omitted fields will be zero-valued.
It’s idiomatic to encapsulate new struct creation in constructor functions.
Access struct fields with a dot.
Structs are mutable.
If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type. This technique is commonly used for testing.
Now that we can run and build basic Rust programs, let’s learn more about the language.