Menu
CoddyTech

Encapsulation

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

C# properties can expose controlled access without a public field. Rust has methods rather than property syntax, and its privacy boundary is a module rather than only the enclosing type. The token module keeps the code private and offers an observer that reveals only whether the token is active. A caller cannot directly write the private code, but sibling code inside the defining module can access it. Keep the module small when that boundary matters. Encapsulation is useful because callers depend on a behavior instead of a representation; the implementation could later store activity differently without changing the observer's contract. C# private and Rust field privacy are therefore similar design tools with different access rules. A read method taking &self communicates shared access. The example has no deposit, withdrawal or balance operations and does not validate the exercise's transactional state changes for you.

Complete C# program:

using System;
class Token {
    private readonly string code;
    public Token(string value) { code = value; }
    public bool Active { get { return code != ""; } }
}
class Program {
    static void Main() { Console.WriteLine(new Token("key").Active); }
}

Complete Rust program:

mod token {
    pub struct Token { code: String }
    impl Token {
        pub fn new(code: String) -> Self { Self { code: code } }
        pub fn active(&self) -> bool { !self.code.is_empty() }
    }
}
fn main() {
    let token = token::Token::new(String::from("key"));
    println!("{}", token.active());
}
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 C# Developers

Practice on your own: Online Rust compiler