Menu
CoddyTech

Encapsulation

Lesson 33 of 48 in Coddy's Rust for PHP Developers course.

PHP private properties are controlled by class access rules. Rust privacy follows modules rather than restricting a field solely to one impl block. The public Rust Token hides its secret from the parent module while exposing construction and matching operations. Both examples test matching and nonmatching candidates through the API without exposing direct caller mutation of the secret. Other code in the defining Rust module can access its private fields, so place invariants at the correct module boundary. Encapsulation protects representation choices only when every public operation also preserves the promised rules. A visibility modifier does not replace input validation.

PHP: complete program

<?php
declare(strict_types=1);
final class Token {
    public function __construct(private string $secret) {}
    public function matches(string $candidate): bool { return $this->secret === $candidate; }
}
$token = new Token("mint");
echo ($token->matches("mint") ? "true" : "false"), "\n";
echo ($token->matches("sage") ? "true" : "false"), "\n";

Rust: complete program

mod access {
    pub struct Token { secret: String }
    impl Token {
        pub fn fixed() -> Self { Token { secret: String::from("mint") } }
        pub fn matches(&self, candidate: &str) -> bool { self.secret == candidate }
    }
}
fn main() {
    let token = access::Token::fixed();
    println!("{}", token.matches("mint"));
    println!("{}", token.matches("sage"));
}

Rust module privacy is not PHP private-to-class visibility; choose the boundary deliberately.

challenge icon

Challenge

Easy

Implement wallet::Wallet with private balance. Wallet::new(balance: i32) -> Option<Wallet> rejects negative balances. balance(&self) -> i32 reads the balance. deposit(&mut self, amount: i32) -> bool rejects negative amounts and otherwise adds them. withdraw(&mut self, amount: i32) -> bool rejects negative amounts or amounts above the balance. Every rejected operation leaves state unchanged; zero is accepted. solve reads a nonnegative initial balance followed by command pairs d amount or w amount. Return each result as true:balance or false:balance on its own line, followed by balance:n. All values and intermediate balances fit i32.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, wallet.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod wallet;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert!(wallet::Wallet::new(-17).is_none());
let mut a = wallet::Wallet::new(43).unwrap(); let b = wallet::Wallet::new(6).unwrap();
assert!(!a.withdraw(44)); assert_eq!(a.balance(), 43);
assert!(!a.withdraw(-2)); assert!(!a.deposit(-8)); assert_eq!(a.balance(), 43);
assert!(a.withdraw(43)); assert!(a.withdraw(0)); assert_eq!(a.balance(), 0);
assert!(a.deposit(11)); assert!(a.deposit(0)); assert_eq!(a.balance(), 11);
assert_eq!(b.balance(), 6); assert!(a.withdraw(4)); assert_eq!(a.balance(), 7);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for PHP Developers

Practice on your own: Online Rust compiler