Menu
CoddyTech

カプセル化

Coddyの「C開発者のためのRust」コースのレッスン 33/48。

Rustでは、モジュール境界によってプライバシーが保たれます。公開構造体でも、フィールドを非公開にして、規則を維持する操作だけを公開できます。Cでは、不完全型を使ってヘッダー内で構造体の定義を隠し、実装関数から完全なレコードにアクセスできます。Rustでは、モジュールとpubを使って、その境界を直接表現します。このコードでは、呼び出し側のコードに保存された文字列への直接アクセスを許さずに、タグの比較を公開しています。失敗する可能性のある操作では、まず検証し、すべてのチェックが成功した後にのみ変更を加えます。

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"));
}

構造体にpubを付けても、非公開フィールドは公開されません。別のモジュールから公開メソッドを呼び出してください。

challenge icon

チャレンジ

簡単

残高を非公開にした wallet::Wallet を実装してください。Wallet::new(balance: i32) -> Option<Wallet> は負の残高を拒否します。balance(&self) -> i32 は残高を読み取ります。deposit(&mut self, amount: i32) -> bool は負の金額を拒否し、それ以外の場合はその金額を加算します。withdraw(&mut self, amount: i32) -> bool は負の金額、または残高を超える金額を拒否します。拒否された操作では状態は変化しません。0は受け入れられます。solve は、0以上の初期残高に続いて、コマンドのペア d amount または w amount を読み取ります。それぞれの結果を独立した行に true:balance または false:balance として返し、その後に balance:n を返してください。すべての値と途中の残高は i32 の範囲内に収まります。

必要な公開APIを実装し、exercise::solve(input: &str) -> String の結果を末尾の改行なしで返してください。編集可能なコード内で出力しないでください。ロックされたドライバーは必要なAPIを個別に検査し、標準入力をすべて読み取り、返されたテキストを末尾に改行を1つ付けて出力します。

コードは exercise.rs と wallet.rs に記述してください。main.rs には提供された入出力コードがあり、編集できません。

自分で試してみよう

#![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();
    // PUBLIC API の検証開始
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);
    // PUBLIC API の検証終了
    println!("{}", exercise::solve(&input));
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのRustのすべてのレッスン

自分で練習してみよう: Rustオンラインコンパイラ