Screen構造体
CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 52/61。
チャレンジ
簡単さあ、すべての UI コンポーネントをまとめる時です!trait objects を使用して、さまざまな描画可能なコンポーネントのコレクションを保持できる Screen struct を作成します。ここで Vec<Box<dyn Draw>> の力が本領を発揮します。複数の component type を管理する 1 つのコレクションです。
成長中のプロジェクトに新しい module を追加します。
draw.rs: 以前の challenge で作成したDrawtrait。text_field.rs:Text: {content}を出力するTextFieldcomponent。button.rs:Button: {label} (width: {width})を出力するButtoncomponent。screen.rs: type がVec<Box<dyn Draw>>の public fieldcomponentsを保持するScreenstruct を Create します。empty な screen を作成するnewassociated function と、Box<dyn Draw>を takes して components vector に追加するaddmethod を Implement します。main.rs: すべての module をまとめます。Screenを Create し、TextFieldとButtonを追加してから、screen の components を Iterate し、それぞれに対してdraw()を call します。
Screen は trait objects を保存する必要があるため、Draw trait とともに dyn keyword を using します。add method は components vector を変更するため、&mut self を takes する必要があります。
次の input が提供されます。
- First line: text field の content
- Second line: button の label
- Third line: button の width(number として)
output には、追加された順序で各 component をそれぞれ独自の line に表示してください。
Text: Hello
Button: Click Me (width: 80)自分で試してみよう
mod draw;
mod text_field;
mod button;
mod screen;
use draw::Draw;
use text_field::TextField;
use button::Button;
use screen::Screen;
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");
// TODO: Screen::new() を使って Screen を作成する
// TODO: Box::new() でラップした TextField を screen に追加する
// TODO: Box::new() でラップした Button を screen に追加する
// TODO: screen.components を反復処理し、各コンポーネントで draw() を呼び出す
}オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ