TL ; DR:
A member function (or method) is a function defined for a struct. It can read and write the object's data members.
Define methods in an
implblock; the&selfparameter is what lets you call them with a dot (addpubif other modules need to call them):struct Dog { pub name: String, } impl Dog { fn new(name: &str) -> Dog { Dog { name: name.to_string() } } pub fn bark(&self) { println!("Woof! I am {}", self.name); } }Call it on an object with the dot operator:
dog.bark();
Full lesson:
So far you've added data to a struct with member variables and a constructor. The other half of OOP is behavior — actions an object can perform. That's what member functions are for.
Your task
Add a bark() member function that prints "Woof! I am " followed by the dog's name.
Woof! I am RexFree plan: 30 tutor messages. PRO is unlimited.
