Encapsulation
Lesson 33 of 48 in Coddy's Rust for TypeScript Developers course.
TypeScript private is usually a static access restriction, whereas JavaScript hash-prefixed private fields have runtime privacy. Rust field visibility is checked through its module system. A public struct can hide its fields and expose only methods, preventing outside modules from constructing invalid states directly. The standalone Rust example uses an inline module to show the boundary explicitly. Both programs expose a fixed display mode through an accessor. The Rust parent cannot read the private field just because it can name the public type. Keeping fields private is useful only when the methods preserve the intended contract. Visibility is not a substitute for validating inputs, and it does not introduce inheritance or runtime property lookup.
Complete standalone TypeScript program:
class Theme {
#mode = "quiet";
mode(): string { return this.#mode; }
}
console.log(new Theme().mode());
TypeScript output:
quiet
Complete standalone Rust program:
mod theme {
pub struct Theme { mode: &'static str }
impl Theme {
pub fn new() -> Theme { Theme { mode: "quiet" } }
pub fn mode(&self) -> &str { self.mode }
}
}
fn main() { println!("{}", theme::Theme::new().mode()); }
Rust output:
quiet
Challenge
EasyImplement 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for TypeScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap7Structs and State
Structs and FieldsImpl and ConstructorsMethods and ReceiversEncapsulationComposition and OwnershipReceipt State Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler