Start learning free

LESSON 186 OF 348 · OBJECT-ORIENTED PROGRAMMING

Member Variables in Rust in Rust

Lesson

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 pub access 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,
}
  • pub is an access modifier — every field declared with it is accessible from outside the struct. Without it, fields default to private in a struct.

  • 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) with pub visibility. Then in mainFunction, set them on the dog object so the pre-filled println! prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check

    Class Fields in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free