스크린 실행하기
Coddy Rust 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 61개 중 53번째.
챌린지
쉬움문서 시스템 프로젝트의 마지막 단계에 도달하신 것을 축하드립니다! 여러분은 Draw 트레이트, TextField, Button, 그리고 Screen이라는 모든 개별 조각들을 구축했습니다. 이제 단 한 번의 메서드 호출로 Screen이 모든 구성 요소를 한꺼번에 렌더링할 수 있는 기능을 부여할 차례입니다.
Screen 구조체에 run 메서드를 추가하여 프로젝트를 완성하게 됩니다. 이 메서드는 화면에 저장된 모든 구성 요소를 반복하며 각 구성 요소에 대해 draw()를 호출하여 전체 문서 시스템이 작동하도록 만듭니다.
프로젝트 파일 구성:
draw.rs:draw메서드가 포함된Draw트레이트입니다.text_field.rs:Text: {content}를 출력하는TextField구성 요소입니다.button.rs:Button: {label} (width: {width})를 출력하는Button구성 요소입니다.screen.rs:new및add메서드가 포함된Screen구조체입니다.&self를 매개변수로 받고 컬렉션의 모든 구성 요소에 대해draw()를 호출하는run메서드를 추가하세요.main.rs: 모든 것을 하나로 모읍니다.Screen을 생성하고, 구성 요소를 추가한 다음,run()을 호출하여 전체 화면을 한 번에 렌더링합니다.
run 메서드는 렌더링 로직을 Screen 내부에 캡슐화하여 main 함수를 깔끔하고 단순하게 만듭니다. main에서 수동으로 구성 요소를 반복하는 대신, screen.run()만 호출하면 됩니다.
다음 입력값이 제공됩니다:
- 첫 번째 줄: 텍스트 필드의 내용 (content)
- 두 번째 줄: 버튼의 라벨 (label)
- 세 번째 줄: 버튼의 너비 (width, 숫자 형식)
출력은 추가된 순서대로 각 구성 요소를 별도의 줄에 표시해야 합니다:
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();
}
}