Menu
Coddy logo textTech

Screen 구조체

Coddy Rust 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 61개 중 52번째.

challenge icon

챌린지

쉬움

이제 모든 UI 컴포넌트를 하나로 모을 시간입니다! 트레이트 객체(trait objects)를 사용하여 다양한 그리기 가능한 컴포넌트 컬렉션을 보유할 수 있는 Screen 구조체를 만들 것입니다. 이것이 바로 Vec<Box<dyn Draw>>의 힘이 발휘되는 부분입니다. 하나의 컬렉션으로 여러 컴포넌트 타입을 관리할 수 있습니다.

성장 중인 프로젝트에 새로운 모듈을 추가하게 됩니다:

  • draw.rs: 이전 챌린지에서 만든 Draw 트레이트입니다.
  • text_field.rs: Text: {content}를 출력하는 TextField 컴포넌트입니다.
  • button.rs: Button: {label} (width: {width})를 출력하는 Button 컴포넌트입니다.
  • screen.rs: Vec<Box<dyn Draw>> 타입의 공용 필드 components를 가진 Screen 구조체를 만듭니다. 빈 화면을 생성하는 new 연관 함수와, Box<dyn Draw>를 인자로 받아 components 벡터에 추가하는 add 메서드를 구현하세요.
  • main.rs: 모든 모듈을 하나로 합칩니다. Screen을 생성하고, TextFieldButton을 추가한 다음, 화면의 컴포넌트들을 순회하며 각각의 draw()를 호출하세요.

Screen은 트레이트 객체를 저장해야 하므로, Draw 트레이트와 함께 dyn 키워드를 사용해야 합니다. add 메서드는 components 벡터를 수정하므로 &mut self를 인자로 받아야 합니다.

다음 입력값이 제공됩니다:

  • 첫 번째 줄: 텍스트 필드의 내용 (content)
  • 두 번째 줄: 버튼의 라벨 (label)
  • 세 번째 줄: 버튼의 너비 (width, 숫자)

출력은 추가된 순서대로 각 컴포넌트를 개별 줄에 표시해야 합니다:

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() 호출
}

Object Oriented Programming의 모든 레슨