9.2 Defining and Instantiating Structs
9.2.1 Struct Definitions
Ordinary structs in Rust are defined with the struct
keyword, followed by named fields within curly braces {}
. Each field specifies a type:
struct StructName {
field1: Type1,
field2: Type2,
// additional fields...
}
This form is commonly used for structs whose fields are explicitly named. Rust also supports tuple structs, which do not name their fields—these will be covered later in this chapter.
Here is a concrete example:
struct Person {
name: String,
age: u8,
}
- Field Naming Conventions: Typically, use
snake_case
. - Types: Fields can hold any valid Rust type, including primitive, compound, or user-defined types.
- Scope: Struct definitions often appear at the module scope, but they can be defined locally within functions if required.
9.2.2 Instantiating Structs and Accessing Fields
To create an instance, you must supply initial values for every field:
let someone = Person {
name: String::from("Alice"),
age: 30,
};
You access struct fields using dot notation, similar to C:
println!("Name: {}", someone.name);
println!("Age: {}", someone.age);
9.2.3 Mutability
When you declare a struct instance as mut
, all fields become mutable; you cannot make just one field mutable on its own:
struct Person { name: String, age: u8, } fn main() { let mut person = Person { name: String::from("Bob"), age: 25, }; person.age += 1; println!("{} is now {} years old.", person.name, person.age); }
If you need a mix of mutable and immutable data within a single object, consider splitting the data into multiple structs or using interior mutability (covered in a later chapter).