Start learning free

LESSON 290 OF 679 · FUNCTIONS & CLASSES

Member Variables in Rust

Lesson

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 pub if 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 be mut)



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,
}
  • pub is 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, like mainFunction here, can still use it.

  • name: String is 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 old
STEP 1 OF 2
    Ctrl + Enter to check