CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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());
}

Expected output

Ece 50

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the benefit of keeping the balance private?

  • The balance can only change through methods following the rules (yatir, cek) Correct answer
  • It runs faster
  • Memory saving
  • The compiler requires it

Explanation: Encapsulation protects invariants: for example, the balance never goes negative.

2 Public field

Question
pub struct Hesap {
    ____ sahip: String,
    bakiye: i64,
}
Answer
pub struct Hesap {
    pub sahip: String,
    bakiye: i64,
}

Explanation: Struct fields are opened individually with pub.

3 Item and outside access

Term Meaning
pub sahip Readable and writable
bakiye (no pub) Inaccessible
pub enum Tur All variants open
pub fn bakiye(&self) Read-only access

All lessons in Intermediate