트레이트 객체
Coddy의 Python 개발자를 위한 Rust 코스 레슨. 48개 중 38번째.
Python 리스트는 서로 관련 없는 객체를 담고 공통 메서드를 동적으로 호출할 수 있습니다. Rust 벡터에는 하나의 요소 타입이 필요하지만, 그 타입은 적절한 트레이트를 구현하는 값을 소유하는 포인터인 Box<dyn Label>일 수 있습니다. 각 객체에는 동적 메서드 디스패치에 필요한 정보가 담겨 있으며, 구체적인 값은 크기와 타입이 서로 다를 수 있습니다. 빌린 &dyn Label은 값 자체를 소유하거나 할당하지 않고 동적 디스패치를 제공합니다. 반면, 제네릭 T: Label 매개변수는 해당 인스턴스화에 사용할 구체적인 T를 선택합니다. dyn과 호환되는 트레이트만 트레이트 객체를 만들 수 있습니다. 트레이트 객체는 크기가 정해져 있지 않으며, 참조와 박스가 크기가 정해진 포인터를 제공합니다. T: Label + ?Sized 제약이 있는 빌린 제네릭 매개변수도 트레이트 객체를 받을 수 있습니다. 이 예제에서는 두 가지 라벨 생성자를 함께 사용해 실행 중인 숫자 상태를 변환하지 않고 각 결과를 출력합니다.
Python: 완전한 프로그램
class Sun:
def label(self):
return "day"
class Moon:
def label(self):
return "night"
for item in [Sun(), Moon()]:
print(item.label())Rust: 완전한 프로그램
trait Label { fn label(&self) -> &'static str; }
struct Sun;
struct Moon;
impl Label for Sun { fn label(&self) -> &'static str { "day" } }
impl Label for Moon { fn label(&self) -> &'static str { "night" } }
fn main() {
let items: Vec<Box<dyn Label>> = vec![Box::new(Sun), Box::new(Moon)];
for item in &items { println!("{}", item.label()); }
}Box는 소유권과 간접 참조를 제공하고, dyn은 동적 디스패치를 제공합니다. 트레이트 객체가 클래스 상속 계층 구조를 의미하는 것은 아닙니다.
챌린지
쉬움adjuster::Adjuster를 apply(&self, value: i32) -> i32로 정의하세요. offset::Offset { pub amount: i32 }에 이를 구현하여 해당 amount를 더하고, ceiling::Ceiling { pub maximum: i32 }에 구현하여 value와 maximum 중 더 작은 값을 반환하세요. pipeline::run(value: i32, steps: &[Box<dyn Adjuster>]) -> i32은 전달된 각 객체를 슬라이스 순서대로 한 번씩 적용하고, 각 결과를 다음 객체에 전달합니다. 파이프라인이 비어 있으면 입력값을 반환합니다. solve는 처음 정수 하나와 완전한 add amount 또는 cap maximum 쌍을 차례로 읽습니다. 소유권을 갖는 트레이트 객체를 만들고 최종값을 반환하세요. 모든 입력과 중간 결과는 i32 범위에 들어갑니다.
필수 공개 API를 구현하고 exercise::solve(input: &str) -> String의 결과를 마지막 개행 없이 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 잠금 처리된 드라이버는 필수 API를 각각 확인하고, stdin 전체를 읽은 뒤 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다.
코드는 exercise.rs, adjuster.rs, offset.rs, ceiling.rs, pipeline.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod adjuster;
mod offset;
mod ceiling;
mod pipeline;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
use adjuster::Adjuster;
assert_eq!(offset::Offset { amount: -7 }.apply(19), 12);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(22), 14);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(-3), -3);
struct Times(i32);
impl adjuster::Adjuster for Times { fn apply(&self, v: i32) -> i32 { v * self.0 } }
let steps: Vec<Box<dyn adjuster::Adjuster>> = vec![Box::new(offset::Offset { amount: 4 }), Box::new(Times(3)), Box::new(ceiling::Ceiling { maximum: 32 })];
assert_eq!(pipeline::run(5, &steps), 27); assert_eq!(pipeline::run(8, &steps), 32);
assert_eq!(pipeline::run(5, &steps), 27);
assert_eq!(pipeline::run(-91, &[]), -91);
// PUBLIC API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Python 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러