Start learning free

LESSON 636 OF 679 · OBJECT-ORIENTED PROGRAMMING

Access Specifiers in Rust

Lesson

TL ; DR:

  • Rust has two levels of visibility: private (the default) and pub. There are no public:/private: section labels; you mark each item or field individually.


  • By default, struct fields and methods are private to the module where they are defined; add pub to make them visible to other modules:

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

  • Code in another module can't read rex.name (a compile error), but it can call a pub method such as rex.get_name(). In this lesson everything is in one file, so mainFunction could technically read rex.name too; use get_name() anyway, as that is the habit the lesson teaches.



Full lesson:

Visibility in Rust works at the level of modules: a private item can be used anywhere inside the module that defines it, and pub opens it up to the outside. Keeping fields private and exposing methods lets a struct protect its own data.


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 pub, any client in another module 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 &self.name.

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