Menu
Coddy logo textTech

Screen 구조체

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

challenge icon

챌린지

쉬움

이제 모든 UI components를 하나로 모을 시간입니다! trait objects를 사용하여 서로 다른 drawable components의 collection을 담을 수 있는 Screen struct를 만듭니다. 여기서 Vec<Box<dyn Draw>>의 강력한 기능이 진가를 발휘합니다. 여러 component type을 관리하는 하나의 collection입니다.

성장 중인 project에 새 module을 추가합니다:

  • draw.rs: 이전 challenge에서 만든 Draw trait입니다.
  • text_field.rs: Text: {content}를 출력하는 TextField component입니다.
  • button.rs: Button: {label} (width: {width})를 출력하는 Button component입니다.
  • screen.rs: Vec<Box<dyn Draw>> type의 public field components를 보유하는 Screen struct를 Create합니다. 빈 screen을 생성하는 new associated function과 Box<dyn Draw>를 takes하여 components vector에 추가하는 add method를 Implement합니다.
  • main.rs: 모든 module을 하나로 모읍니다. Screen을 Create하고, TextFieldButton을 추가한 다음, screen의 components를 Iterate하며 각 component에서 draw()를 call합니다.

Screen은 trait objects를 저장해야 하므로 Draw trait과 함께 dyn keyword를 사용합니다. add method는 components vector를 수정하므로 &mut self를 takes해야 합니다.

다음 input이 제공됩니다:

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

output은 추가된 순서대로 각 component를 자체 줄에 표시해야 합니다:

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