How to Add a Human Struct to Your Rust Program
What the reader will be able to do: Define a Human struct with name and age fields and use it in a Rust program.
Prerequisites
- Basic Rust program structure (from previous tutorial)
- Understanding of
fn main()andprintln!
Steps
-
Define the Human struct
Opensrc/main.rsand replace its contents with:struct Human { name: String, age: u32, } fn main() { let person = Human { name: String::from("Alice"), age: 30, }; println!("Name: {}", person.name); println!("Age: {}", person.age); } -
Compile and run
Run:cargo runExpected output:
Name: Alice Age: 30 -
Modify the struct fields
Change thenameandagevalues inmain():let person = Human { name: String::from("Bob"), age: 25, };Re-run
cargo runto see the updated output.
Pitfalls
- Forgetting to use
String::from()for string literals (causes compilation errors) - Using
i32instead ofu32for age (Rust requires unsigned integers for non-negative values) - Not initializing struct fields in the correct order
To go further
- Learn about Rust's
OptionandResulttypes for handling missing data - Explore how to implement methods on structs using
implblocks
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 |
|