How to Change the Values of an Existing Person in Your Rust Program
What the reader will be able to do: Modify the name and age values of an existing Human struct instance using mutability.
Prerequisites
- Basic understanding of Rust structs and mutability (from previous tutorials)
- Familiarity with
letbindings and variable reassignment
Steps
-
Create a mutable
Humaninstance
Insrc/main.rs, define aHumanwithmut:let mut person = Human { name: String::from("Alice"), age: 30, }; -
Modify the values directly
Change the fields using dot notation:person.name = String::from("Bob"); person.age = 25; -
Print the updated values
println!("Name: {}", person.name); println!("Age: {}", person.age); -
Compile and run
Execute:cargo runExpected output:
Name: Bob Age: 25
Pitfalls
- Forgetting
mutin theletbinding (causes compilation errors) - Trying to modify immutable references (e.g.,
&Humaninstead of&mut Human) - Not passing
&mut personto functions (requires mutable reference)
To go further
- Learn about Rust's
clone()method for deep copying structs - Explore how to implement
FromandIntotraits for type conversion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|