Menu
Coddy logo textTech

メソッドチェーン

CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 6/61。

これまで、私たちの mutable methods は struct を変更し、何も返しませんでした。しかし、同じインスタンスに対して複数のメソッドを続けて呼び出したい場合はどうでしょうか?self への参照を返すことで、method chaining が可能になります。これは、複数のメソッド呼び出しを 1 つの expression の中でつなげて記述するパターンです。

重要なのは、&mut self メソッドが &mut Self を返すようにすることです。

struct Config {
    debug: bool,
    timeout: u32,
}

impl Config {
    fn new() -> Config {
        Config { debug: false, timeout: 30 }
    }
    
    fn set_debug(&mut self, value: bool) -> &mut Self {
        self.debug = value;
        self
    }
    
    fn set_timeout(&mut self, seconds: u32) -> &mut Self {
        self.timeout = seconds;
        self
    }
}

各methodはstructを変更し、その後selfを返します。これは同じインスタンスへのmutableな参照です。これにより、次のmethod呼び出しで直ちにそのインスタンスへの処理を続けられます。

fn main() {
    let mut config = Config::new();
    
    config.set_debug(true).set_timeout(60);
    
    println!("Debug: {}, Timeout: {}", config.debug, config.timeout);
    // 出力: Debug: true, Timeout: 60
}

three 個の別々の文を書く代わりに、すべてを一つの流れるような line で設定します。この「ビルダースタイル」のパターンは、多くのオプションの settings を持つオブジェクトを setting up するときに特に便利で、コードをより簡潔で読みやすくできます。

challenge icon

チャレンジ

簡単

TextStyle structを、3つのフィールド(bold(bool)、italic(bool)、size(u32))付きでCreateしてください。

TextStyleのimplementation blockを、次の内容でAddしてください。

  • newboldfalseitalicfalsesize12に設定したTextStyleを返すassociated function
  • set_bold&mut selfbool値を受け取り、boldフィールドを設定し、chaining用に&mut Selfを返す
  • set_italic&mut selfbool値を受け取り、italicフィールドを設定し、chaining用に&mut Selfを返す
  • set_size&mut selfu32値を受け取り、sizeフィールドを設定し、chaining用に&mut Selfを返す

3つの入力を受け取ります。

  • 1行目:bold setting(trueまたはfalse
  • 2行目:italic setting(trueまたはfalse
  • 3行目:フォントサイズ(u32)

newをusingしてmutableなTextStyleをCreateし、その後method chainingを使用して、single expressionですべての3つのsettingsをapplyしてください。以下に示すformatで最終状態をPrintしてください。

Expected output format:

Bold: {bold}, Italic: {italic}, Size: {size}

自分で試してみよう

use std::io;

// TODO: ここで TextStyle 構造体を定義する


// TODO: TextStyle の実装ブロックを追加する。以下を含む:
// - new() 関連関数
// - set_bold() メソッド
// - set_italic() メソッド
// - set_size() メソッド


fn main() {
    let mut input = String::new();
    
    // 太字設定を読み取る
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let bold: bool = input.trim().parse().expect("Invalid bool");
    input.clear();
    
    // 斜体設定を読み取る
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let italic: bool = input.trim().parse().expect("Invalid bool");
    input.clear();
    
    // サイズ設定を読み取る
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let size: u32 = input.trim().parse().expect("Invalid u32");
    
    // TODO: new() を使って可変の TextStyle を作成し、メソッドチェーンを使用する
    // 1つの式ですべての3つの設定を適用する
    
    
    // TODO: 次の形式で結果を出力する: Bold: {bold}, Italic: {italic}, Size: {size}
    
}
quiz icon腕試し

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

オブジェクト指向プログラミングのすべてのレッスン

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