트레이트 객체
Coddy의 C++ 개발자를 위한 Rust 코스 레슨. 48개 중 38번째.
C++의 가상 디스패치는 파생 객체에 접근할 때 기본 클래스 참조나 소유 스마트 포인터를 흔히 사용하며, 기본 클래스 소유자를 통해 삭제하려면 적절한 가상 소멸자가 필요합니다. Rust의 dyn Trait도 런타임 디스패치를 지원하며, 값에 대한 접근과 그 구현을 위한 메타데이터를 함께 제공합니다. 트레이트 객체는 동적으로 크기가 결정되므로 참조나 Box 같은 소유 포인터를 통해 사용해야 합니다. 박스의 벡터는 서로 다른 구체적인 구현체를 소유할 수 있습니다. 반면 제네릭 코드는 각 인스턴스화마다 구체적인 타입을 선택하며, 일반적으로 정적 디스패치를 사용합니다. 모든 트레이트가 트레이트 객체를 지원하는 것은 아닙니다. 제약되지 않은 제네릭 디스패치를 요구하거나 Self를 그대로 반환하는 메서드는 트레이트 객체 사용을 막을 수 있습니다. Rust 컴파일러는 트레이트 객체를 통해 소멸을 관리합니다. 센서 예제는 서로 독립적인 객체에서 값을 읽고 관측값을 합산하며, 과제에서는 순차 변환 파이프라인을 적용합니다.
완전한 독립형 C++17 프로그램:
#include <iostream>
#include <memory>
#include <vector>
struct Sensor { virtual ~Sensor() = default; virtual int read() const = 0; };
struct Fixed : Sensor { int read() const override { return 4; } };
struct Difference : Sensor { int read() const override { return 9 - 2; } };
int main() {
std::vector<std::unique_ptr<Sensor>> sensors;
sensors.push_back(std::make_unique<Fixed>());
sensors.push_back(std::make_unique<Difference>());
int total = 0;
for (const auto& sensor : sensors) total += sensor->read();
std::cout << total << '\n';
}완전한 독립형 Rust 프로그램:
trait Sensor { fn read(&self) -> i32; }
struct Fixed(i32);
struct Difference(i32, i32);
impl Sensor for Fixed { fn read(&self) -> i32 { self.0 } }
impl Sensor for Difference { fn read(&self) -> i32 { self.0 - self.1 } }
fn main() {
let sensors: Vec<Box<dyn Sensor>> = vec![Box::new(Fixed(7)), Box::new(Difference(9, 4))];
let sum: i32 = sensors.iter().map(|s| s.read()).sum();
println!("{}", sum);
}챌린지
쉬움adjuster::Adjuster를 apply(&self, value: i32) -> i32로 정의하세요. 값에 자신의 amount를 더하는 offset::Offset { pub amount: i32 }와 값과 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를 각각 확인하고, 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러