트레이트 객체
Coddy의 JavaScript 개발자를 위한 Rust 코스 레슨. 48개 중 38번째.
JavaScript의 모든 메서드 호출은 런타임에 이름으로 조회합니다. sound.hear()는 호출할 때마다 객체와 프로토타입 체인에서 hear를 찾으므로, 하나의 배열에 hear를 각기 다르게 구현하는 객체들을 자유롭게 섞어 넣을 수 있습니다. Rust에서는 &dyn Sound 같은 트레잇 객체나 소유권을 갖는 Box<dyn Sound>를 사용해 이러한 런타임 혼합을 표현합니다. 참조 형식은 구현체를 빌리고, 박스 형식은 구현체를 소유하므로 Vec<Box<dyn Sound>>는 여러 객체가 섞인 배열에 대응하는 Rust 표현입니다. 트레잇 객체 호출은 이름으로 조회하는 대신 구체 타입에 맞게 생성된 트레잇 메서드 테이블을 통해 동적 디스패치를 사용하며, 트레잇의 메서드만 호출할 수 있습니다. 이는 컴파일 시 각 인스턴스화마다 구체 타입이 정해지는 제네릭 매개변수와 다릅니다. dyn 호환 트레잇만 이 방식으로 사용할 수 있습니다. 제네릭 메서드나 Self를 반환하는 생성자는 객체를 통해 호출할 수 없습니다. 다음 예제는 단일 사운드에 대해 빌린 트레잇 객체를 전달하며, 상속도 박스도 사용하지 않고 소유자는 빌림보다 오래 살아 있어야 합니다.
완전한 단독 실행 JavaScript 프로그램:
const bell = { hear() { return "ding"; } };
function play(sound) { console.log(sound.hear()); }
play(bell);
JavaScript 출력:
ding
완전한 단독 실행 Rust 프로그램:
trait Sound { fn hear(&self) -> &'static str; }
struct Bell;
impl Sound for Bell { fn hear(&self) -> &'static str { "ding" } }
fn play(sound: &dyn Sound) { println!("{}", sound.hear()); }
fn main() { let bell = Bell; play(&bell); }
Rust 출력:
ding
챌린지
쉬움adjuster::Adjuster를 apply(&self, value: i32) -> i32로 정의하세요. 이를 자체 amount를 더하는 offset::Offset { pub amount: i32 }와 value와 maximum 중 더 작은 값을 반환하는 ceiling::Ceiling { pub maximum: i32 }에 구현하세요. pipeline::run(value: i32, steps: &[Box<dyn Adjuster>]) -> i32는 전달된 각 객체를 슬라이스 순서대로 한 번씩 적용하고, 각 결과를 다음 객체에 전달합니다. 파이프라인이 비어 있으면 입력을 반환합니다. solve는 초기 정수 뒤에 완전한 add amount 또는 cap maximum 쌍이 이어지는 입력을 읽습니다. 소유권을 가진 트레이트 객체를 만들고 최종 값을 반환하세요. 모든 입력과 중간 결과는 i32 범위에 들어갑니다.
필요한 내보내기 API를 구현하고 exercise::solve(input: &str) -> String의 결과를 마지막 줄바꿈 없이 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 잠긴 드라이버는 필요한 API를 독립적으로 확인하고, 표준 입력을 모두 읽은 다음 반환된 텍스트를 마지막에 줄바꿈 하나를 붙여 출력합니다.
코드는 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();
// 공개 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);
// 공개 API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러