Menu
Coddy logo textTech

스크린 실행하기

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 53번째.

challenge icon

챌린지

쉬움

Document System 프로젝트의 마지막 단계에 도달한 것을 축하합니다! 이제 모든 개별 구성 요소를 완성했습니다. Draw trait, TextField, Button, 그리고 Screen입니다. 이제 Screen이 단일 method 호출로 모든 component를 한 번에 렌더링할 수 있도록 만들 차례입니다.

Screen struct에 run method를 추가하여 프로젝트를 완성하게 됩니다. 이 method는 screen에 저장된 모든 component를 순회하며 각 component에 draw()를 호출하여 전체 document system이 작동하도록 합니다.

프로젝트 파일:

  • draw.rs: draw method가 포함된 Draw trait입니다.
  • text_field.rs: Text: {content}를 출력하는 TextField component입니다.
  • button.rs: Button: {label} (width: {width})을 출력하는 Button component입니다.
  • screen.rs: newadd method가 포함된 Screen struct입니다. &self를 takes하고 collection의 every component에 draw()를 calls하는 run method를 추가하세요.
  • main.rs: 모든 것을 함께 구성합니다. Screen을 생성하고, component를 추가한 다음, run()을 call하여 전체 screen을 한 번에 렌더링합니다.

run method는 렌더링 로직을 Screen 내부에 캡슐화하므로 main function이 깔끔하고 단순해집니다. main에서 component를 수동으로 순회하는 대신 screen.run()만 호출하면 됩니다.

다음 입력이 제공됩니다:

  • 첫 번째 줄: text field의 content
  • 두 번째 줄: button의 label
  • 세 번째 줄: button의 width (숫자)

출력에는 추가된 순서대로 각 component가 자체 줄에 표시되어야 합니다:

Text: Dashboard
Button: Save (width: 120)
요구되는 출력 형식: [번역된 content]

직접 해보기

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 컴파일러