9.2 Instantiating and Using Structs
9.2.1 Creating Instances
You can create an instance of a struct by specifying the struct's name and providing values for its fields.
let variable_name = StructName {
field1: value1,
field2: value2,
// ...
};
- Field Order: Fields can be specified in any order when creating an instance.
Example:
struct Person { name: String, age: u8, } fn main() { let person = Person { age: 30, name: String::from("Alice"), }; }
- The fields
age
andname
are specified in a different order than in the struct definition, which is allowed.
9.2.2 Field Initialization and Access
Initializing Fields
All fields must be initialized when creating an instance, unless the struct update syntax (discussed later) is used.
Accessing Fields
You can access fields using dot notation.
println!("Name: {}", person.name);
println!("Age: {}", person.age);
9.2.3 Mutability
In Rust, the mutability of a struct instance applies to the entire instance, not to individual fields. You cannot have a struct instance where some fields are mutable and others are immutable. To modify any field within a struct, the entire instance must be declared as mutable using the mut
keyword.
Example:
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); }
- Note: The
mut
keyword makes the entireperson
instance mutable, allowing modification of any of its fields.
If you need to have some data that is mutable and some that is not, you may need to redesign your code, possibly by splitting the data into different structs or by using interior mutability patterns (which we will discuss in a later chapter).
Comparison with C
In C, you can modify struct fields if the variable is not declared const
.
C Code:
struct Person person = { "Bob", 25 };
person.age += 1;
printf("%s is now %d years old.\n", person.name, person.age);