Start learning free

LESSON 188 OF 348 · OBJECT-ORIENTED PROGRAMMING

Access Specifiers in Rust in Rust

Lesson

TL ; DR:

  • C++ has three access specifiers: public:, private:, and protected:. They appear as labels in the class body and apply to everything below them until the next label.


  • By default, members of a class are private (and members of a struct are public):

    struct Dog {
        name: String,  // private by default (no pub keyword)
    }
    impl Dog {
        fn new(name: String) -> Dog { Dog { name } }
        fn get_name(&self) -> &str { &self.name }
    }
    

  • Outside the class, rex.name is a compile error. Use rex.get_name() instead.



Full lesson:

Access specifiers in C++ work like access modifiers in Java/C#, but with different syntax — they're section labels rather than per-member modifiers.


struct BankAccount {
    balance: f64,  // private by default
}
impl BankAccount {
    fn deposit(&mut self, amount: f64) {
        if amount < 0.0 { return; }
        self.balance += amount;
    }
    fn get_balance(&self) -> f64 { self.balance }
}

If balance were public, any client could just write account.balance = -1000.0; and corrupt the state.


Your task

The Dog struct has its name field private by default. Add a fn get_name(&self) -> &str method in the impl block that returns name.

Dog's name: Rex
STEP 1 OF 2
    Ctrl + Enter to check

    Access Modifiers 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