TL ; DR:
Rust has two levels of visibility: private (the default) and
pub. There are nopublic:/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
pubto 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 apubmethod such asrex.get_name(). In this lesson everything is in one file, somainFunctioncould technically readrex.nametoo; useget_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: RexFree plan: 30 tutor messages. PRO is unlimited.
