Menu
CoddyTech

Encapsulation

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

Rust privacy is enforced at module boundaries. A public struct can keep its fields private and expose only operations that preserve its rules. In C, headers can hide a struct definition behind an incomplete type, while implementation functions access the complete record. Rust expresses that boundary directly with modules and pub. This code exposes a tag comparison without giving the calling code direct access to the stored string. For operations that can fail, validate first and mutate only after all checks succeed.

C

#include <stdio.h>
#include <string.h>
struct Tag;
int tag_matches(const struct Tag *tag, const char *text);
struct Tag { const char *text; };
int tag_matches(const struct Tag *tag, const char *text) { return strcmp(tag->text, text) == 0; }
int main(void) {
    struct Tag tag = {"blue"};
    printf("%d %d\n", tag_matches(&tag, "blue"), tag_matches(&tag, "Blue"));
    return 0;
}

Rust

mod tag {
    pub struct Tag { text: String }
    impl Tag {
        pub fn new(text: &str) -> Tag { Tag { text: text.to_string() } }
        pub fn matches(&self, text: &str) -> bool { self.text == text }
    }
}
fn main() {
    let t = tag::Tag::new("blue");
    println!("{} {}", t.matches("blue"), t.matches("Blue"));
}

Putting pub on a struct does not expose private fields. Call its public methods from another module.

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