버튼 컴포넌트
Coddy Rust 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 61개 중 51번째.
챌린지
쉬움두 번째 UI 컴포넌트인 Button을 추가하여 문서 시스템(Document System)을 계속 구축해 보겠습니다. TextField와 마찬가지로, 이 컴포넌트도 Draw 트레이트를 구현하여 서로 다른 타입이 어떻게 공통 인터페이스를 공유할 수 있는지 보여줄 것입니다.
다른 모듈 파일을 추가하여 프로젝트를 확장하게 됩니다:
draw.rs: 이전 챌린지에서 작성한Draw트레이트를 유지합니다.text_field.rs:TextField구조체와 그Draw구현을 유지합니다.button.rs: 두 개의 공개 필드label(String타입)과width(u32타입)를 가진Button구조체를 생성합니다.Button에 대해Draw트레이트를 구현하여,draw()를 호출했을 때Button: {label} (width: {width})형식으로 버튼이 출력되도록 하세요.main.rs: 세 모듈을 모두 가져옵니다.TextField와Button을 모두 생성한 다음, 각각에 대해draw()를 호출하여 두 컴포넌트를 렌더링합니다.
button 모듈은 TextField에서 했던 것과 마찬가지로 crate::draw::Draw를 사용하여 Draw 트레이트에 접근해야 합니다.
다음과 같은 입력이 제공됩니다:
- 첫 번째 줄: 텍스트 필드의 내용(content)
- 두 번째 줄: 버튼의 라벨(label)
- 세 번째 줄: 버튼의 너비(width, 숫자)
출력은 텍스트 필드를 먼저 표시하고, 그 다음 줄에 버튼을 표시해야 합니다:
Text: Welcome
Button: Submit (width: 100)직접 해보기
mod draw;
mod text_field;
mod button;
use draw::Draw;
use text_field::TextField;
use button::Button;
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 text_field = TextField { content };
text_field.draw();
// TODO: `label`과 `width`를 사용하여 Button을 생성한 다음 draw()를 호출하세요
}