Rust
pub
Control visibility with pub.
pub
Visibility is decided item by item. For a struct, pub only opens the type; each field must be marked separately. For an enum, pub opens all variants:
mod banka {
pub struct Hesap {
pub sahip: String, // readable/writable from outside
bakiye: i64, // private
}
pub enum Tur { Vadesiz, Vadeli } // both variants are open
}
A struct with a private field can't be built from outside with Hesap { .. }; a constructor (pub fn new) must be offered.
Getter and constructor
Controlled access to private fields is given through methods:
impl Hesap {
pub fn new(sahip: &str) -> Self {
Self { sahip: sahip.to_string(), bakiye: 0 }
}
pub fn bakiye(&self) -> i64 {
self.bakiye
}
pub fn yatir(&mut self, n: i64) {
if n > 0 {
self.bakiye += n;
}
}
}
Code inside the module can always access private fields in the same module.
Exercise Bank module
Inside mod banka, write Hesap with a pub sahip field and a private bakiye field; add the methods new, bakiye and yatir. In main, open an account for "Ece" and deposit 50; print h.sahip and h.bakiye() separated by a space.
Show example solution
mod banka {
pub struct Hesap {
pub sahip: String,
bakiye: i64,
}
impl Hesap {
pub fn new(sahip: &str) -> Self {
Self {
sahip: sahip.to_string(),
bakiye: 0,
}
}
pub fn bakiye(&self) -> i64 {
self.bakiye
}
pub fn yatir(&mut self, n: i64) {
if n > 0 {
self.bakiye += n;
}
}
}
}
use banka::Hesap;
fn main() {
let mut h = Hesap::new("Ece");
h.yatir(50);
println!("{} {}", h.sahip, h.bakiye());
}
Test yourself
-
What is the benefit of keeping the balance private?
- The balance can only change through methods following the rules (yatir, cek)
- It runs faster
- Memory saving
- The compiler requires it
Show answer
The balance can only change through methods following the rules (yatir, cek) — Encapsulation protects invariants: for example, the balance never goes negative.
-
Public field
pub struct Hesap {
____ sahip: String,
bakiye: i64,
}
Show answer
pub struct Hesap {
pub sahip: String,
bakiye: i64,
}
-
Item and outside access
- pub sahip
- Readable and writable
- bakiye (no pub)
- Inaccessible
- pub enum Tur
- All variants open
- pub fn bakiye(&self)
- Read-only access
Next lesson: File modules