How to Change the Values of a Person in Your Rust Program
What the reader will be able to do: Modify the name and age values of a Human struct at runtime.
Prerequisites
- Basic understanding of Rust structs and
fn main()(from previous tutorials) - Familiarity with
Stringandu32types
Steps
-
Modify the struct initialization in
main()
Opensrc/main.rsand change thepersonstruct values:let person = Human { name: String::from("Charlie"), age: 35, }; -
Add user input to dynamically change values
Replace themain()function with:use std::io; fn main() { println!("Enter your name:"); let mut name = String::new(); io::stdin() .read_line(&mut name) .expect("Failed to read line"); println!("Enter your age:"); let mut age_input = String::new(); io::stdin() .read_line(&mut age_input) .expect("Failed to read line"); let age: u32 = age_input.trim().parse().expect("Please enter a valid number"); let person = Human { name: name.trim().to_string(), age, }; println!("Name: {}", person.name); println!("Age: {}", person.age); } -
Compile and run
Run:cargo runExpected interaction:
Enter your name: David Enter your age: 40 Name: David Age: 40
Pitfalls
- Forgetting to call
.trim()on input strings (leaves newline characters in the output) - Not handling parsing errors with
.expect()(causes crashes on invalid input) - Using
Stringinstead of&strfor input (requires explicit conversion)
To go further
- Learn about Rust's
matchexpressions for validating user input - Explore how to create multiple
Humaninstances in a loop
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|