TL ; DR:
A member variable (or field) is a variable that lives inside a struct. Each value of that struct has its own copy.
Declare fields inside the struct. Add
pubif code in other modules should read and write them:struct Dog { pub name: String, pub age: i32, }Access them on an object with the dot operator:
dog.name = String::from("Rex");(the binding must bemut)
Full lesson:
Right now your Dog struct is just an empty shell — every Dog value you create is identical. We need a way to attach data to each object.
That's what member variables are for. A member variable is a variable that belongs to a struct — and each value created from that struct gets its own copy of every member.
Declaring member variables
struct Dog {
pub name: String,
pub age: i32,
}
pubis a visibility modifier — a field declared with it is accessible from other modules. Without it, a field is private to the module where the struct is defined; code in the same file and module, likemainFunctionhere, can still use it.name: Stringis a regular field declaration.
Reading and writing
let mut dog = Dog { name: String::new(), age: 0 };
dog.name = String::from("Rex"); // write
dog.age = 4;
println!("{}", dog.name); // read
Each object has its own slot for every member, so two dogs can have different names without interfering.
Your task
Update the Dog struct to have two member variables: name (a String) and age (an i32); pub is optional here. Then in mainFunction, set them on the dog value (use "Rex".to_string() for the name) so the pre-filled println! prints:
Rex is 4 years oldFree plan: 30 tutor messages. PRO is unlimited.
