Menu
Coddy logo textTech

ボタンコンポーネント

CoddyのRustジャーニー「Object Oriented Programming」セクションの一部 — レッスン 51/61。

challenge icon

チャレンジ

簡単

2つ目のUIコンポーネントである Button を追加して、ドキュメントシステムの構築を続けましょう。TextField と同様に、このコンポーネントも Draw トレイトを実装し、異なる型がどのように共通のインターフェースを共有できるかを示します。

別のモジュールファイルを追加してプロジェクトを拡張します:

  • draw.rs: 前回のチャレンジの Draw トレイトをそのまま保持します。
  • text_field.rs: TextField 構造体とその Draw 実装を保持します。
  • button.rs: 2つのパブリックフィールド、label (String 型) と width (u32 型) を持つ Button 構造体を作成します。ButtonDraw トレイトを実装し、draw() を呼び出すと Button: {label} (width: {width}) という形式でボタンが表示されるようにします。
  • main.rs: 3つのモジュールすべてを取り込みます。TextFieldButton の両方を作成し、それぞれで draw() を呼び出して両方のコンポーネントをレンダリングします。

button モジュールは、TextField の時と同様に crate::draw::Draw を使用して Draw トレイトにアクセスする必要があります。

以下の入力が提供されます:

  • 1行目:テキストフィールドの内容
  • 2行目:ボタンのラベル
  • 3行目:ボタンの幅(数値として)

出力は、最初にテキストフィールド、次にボタンを、それぞれ個別の行に表示する必要があります:

Text: Welcome
Button: Submit (width: 100)

自分で試してみよう

mod draw;
mod text_field;
mod button;

use draw::Draw;
use text_field::TextField;
use button::Button;

pub struct Label {
    pub text: String,
}

impl Draw for Label {
    fn draw(&self) {
        println!("{}", self.text);
    }
}

fn main() {
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let content = input1.trim().to_string();

    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let label = input2.trim().to_string();

    let mut input3 = String::new();
    std::io::stdin().read_line(&mut input3).expect("Failed to read line");
    let width: u32 = input3.trim().parse().expect("Failed to parse width");

    let text_field = TextField { content };
    text_field.draw();

    // TODO: `label` と `width` を使用して Button を作成し、draw() を呼び出す
    
}

Object Oriented Programmingのすべてのレッスン