スクリーンの実行
CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 53/61。
チャレンジ
簡単Document System プロジェクトの最終ステップまで到達しました。おめでとうございます!個々の要素である Draw trait、TextField、Button、Screen をすべて構築しました。次は、単一のメソッド呼び出しですべての components を一度に描画できるよう、Screen に機能を追加します。
Screen struct に run method を追加して、プロジェクトを完成させます。この method は screen に保存されているすべての components を反復処理し、それぞれに対して draw() を呼び出すことで、document system 全体を動作させます。
プロジェクトのファイル:
draw.rs:drawmethod を持つDrawtrait。text_field.rs:Text: {content}を出力するTextFieldcomponent。button.rs:Button: {label} (width: {width})を出力するButtoncomponent。screen.rs:newとaddmethods を持つScreenstruct。&selfを受け取り、collection 内の every component に対してdraw()を呼び出すrunmethod を追加します。main.rs:すべてをまとめます。Screenを作成し、components を追加して、run()を呼び出し、screen 全体を一度に描画します。
run method は Screen 内に描画ロジックをカプセル化するため、main function をすっきりとシンプルにできます。main で components を手動で反復処理する代わりに、screen.run() を呼び出すだけです。
次の入力が提供されます:
- 1 行目:text field の content
- 2 行目:button の label
- 3 行目:button の width(数値)
出力には、追加された順序で各 component をそれぞれ 1 行に表示してください:
Text: Dashboard
Button: Save (width: 120)自分で試してみよう
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");
let mut screen = Screen::new();
let text_field = TextField { content };
screen.add(Box::new(text_field));
let button = Button { label, width };
screen.add(Box::new(button));
// TODO: 以下の手動イテレーションを screen.run() の単一呼び出しに置き換える
for component in &screen.components {
component.draw();
}
}オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ