기본 구현 오버라이딩
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 32번째.
default implementation은 편리하지만, 때로는 타입에 표준과 다른 동작이 필요합니다. 이런 경우 impl 블록에서 자체 implementation을 제공하여 기본 동작을 override할 수 있습니다.
동일한 시그니처로 메서드를 정의하되, 사용자 지정 로직을 포함하세요:
trait Greet {
fn greet(&self) -> String {
String::from("Hello there!")
}
}
struct Robot {
id: u32,
}
impl Greet for Robot {
fn greet(&self) -> String {
format!("BEEP BOOP. Unit {} online.", self.id)
}
}
Greet가 기본 greet 메서드를 제공하더라도, Robot은 이를 자체 버전으로 완전히 대체합니다. Robot에서 greet()를 호출하면 Rust는 사용자 지정 구현을 사용합니다.
let bot = Robot { id: 42 };
println!("{}", bot.greet()); // 삑 붑. 유닛 42 온라인.
이는 유연성을 제공합니다. default로 만족하는 타입은 아무것도 작성할 필요가 없고, 특수한 동작이 필요한 타입은 필요한 method만 재정의할 수 있습니다. 그래도 이 트레이트는 모든 구현하는 타입에서 해당 method를 사용할 수 있음을 보장합니다.
챌린지
쉬움서로 다른 alert 유형이 자체 message를 사용자 지정할 수 있는 notification system을 만들어 봅시다! default implementation이 있는 trait를 만들고, 한 유형은 default를 사용하고 다른 유형은 custom 동작으로 이를 override하도록 합니다.
코드를 세 개의 파일로 구성합니다:
notifiable.rs: publicNotifiabletrait와 default implementation을 가지는notify(&self) -> Stringmethod를 Define합니다. 이 implementation은"Alert: Something happened!"를 return합니다.alerts.rs: trait를 서로 다르게 implement하는 두 개의 public struct를 Create합니다:GenericAlert: default notification을 사용하는 unit struct (empty impl block)UrgentAlert: publicmessagefield(String)를 가진 struct로, default를 override하여"URGENT: {message}"를 return합니다. 여기서{message}는 저장된 message입니다.
main.rs: module들을 하나로 모으고 두 동작을 모두 보여 줍니다. 제공된 input을 사용하여GenericAlert와UrgentAlert를 Create한 다음, 각각의 notification을 Print합니다.
여기서 핵심은 GenericAlert가 default로부터 동작을 무료로 얻는 반면, UrgentAlert는 impl block에서 method를 Define하여 자체적인 특화 버전을 제공한다는 점입니다.
출력은 다음 format을 따라야 합니다:
Alert: Something happened!
URGENT: {message}예를 들어 input이 Server is down!인 경우:
Alert: Something happened!
URGENT: Server is down!하나의 input을 받습니다. urgent alert의 message입니다.
직접 해보기
mod notifiable;
mod alerts;
use alerts::{GenericAlert, UrgentAlert};
use notifiable::Notifiable;
fn main() {
// 긴급 알림 메시지를 위한 입력 읽기
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let message = input.trim().to_string();
// TODO: GenericAlert 인스턴스 생성
// TODO: 입력 메시지로 UrgentAlert 인스턴스 생성
// TODO: GenericAlert의 알림 출력
// TODO: UrgentAlert의 알림 출력
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러