TL ; DR:
C++ has three access specifiers:
public:,private:, andprotected:. They appear as labels in the class body and apply to everything below them until the next label.By default, members of a
classareprivate(and members of astructarepublic):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.nameis a compile error. Userex.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: RexFree plan: 30 tutor messages. Premium is unlimited.