How to Add a Greeting Method to the Human Structure
What the reader will be able to do: Define a method on the Human struct that prints a personalized greeting.
Prerequisites
- Basic understanding of Rust structs and mutability (from previous tutorials)
- Familiarity with
fn main()andprintln!
Steps
-
Define the
Humanstruct
Opensrc/main.rsand ensure you have:struct Human { name: String, age: u32, } -
Add a method to the
Humanstruct
Replace themain()function with:impl Human { fn greet(&self) { println!("Hello, my name is {} and I am {} years old.", self.name, self.age); } } fn main() { let person = Human { name: String::from("Alice"), age: 30, }; person.greet(); } -
Compile and run
Run:cargo runExpected output:
Hello, my name is Alice and I am 30 years old.
Pitfalls
- Forgetting to use
selfin the method definition - Using
&mut selfinstead of&selfwhen the method doesn't modify the struct - Not implementing the
implblock correctly (missingfnkeyword)
To Go Further
- Learn how to implement multiple methods on the same struct
- Explore how to use
selfin different ways (&self,&mut self,self) - Study how to return values from methods instead of printing them
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 |
|