TL ; DR:
A member variable (or field) is a variable that lives inside a class. Each object of that class has its own copy.
Declare member variables with the
pubaccess modifier so other code can 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");
Full lesson:
Right now your Dog class is just an empty shell — every Dog object 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 class — and each object created from that class gets its own copy of every member.
Declaring member variables
struct Dog {
pub name: String,
pub age: i32,
}
pubis an access modifier — every field declared with it is accessible from outside the struct. Without it, fields default toprivatein astruct.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) with pub visibility. Then in mainFunction, set them on the dog object so the pre-filled println! prints:
Rex is 4 years oldFree plan: 30 tutor messages. Premium is unlimited.