트레이트 객체
Coddy의 C# 개발자를 위한 Rust 코스 레슨. 48개 중 38번째.
C# 인터페이스 참조는 서로 다른 구현 클래스를 가리킬 수 있습니다. Rust의 &dyn Trait도 구체적인 구현 타입을 빌린 트레잇 객체 뒤에 숨기고 동적 디스패치를 사용합니다. Box<dyn Trait>는 객체의 소유권도 가집니다. 동적 디스패치와 소유권 선택은 서로 별개입니다. 트레잇 바운드를 사용하는 제네릭 함수는 일반적으로 각 인스턴스화에서 구체적인 타입을 유지합니다. 트레잇 객체로 사용하는 트레잇은 dyn 호환성 규칙을 충족해야 합니다. 모든 제네릭 API나 자기 자신을 반환하는 트레잇 API를 트레잇 객체를 통해 호출할 수 있는 것은 아닙니다. 예제에서는 서로 다른 두 레이블 제공자를 보관하고 공통 인터페이스를 통해 차례로 사용합니다. Rust의 빌린 객체는 구체적인 소유자의 수명이 뷰 배열보다 길기 때문에 유효한 상태를 유지합니다. 이 특정 뷰에는 힙 할당이 필요하지 않습니다. 동적 디스패치를 선택해도 필드 상속이 추가되는 것은 아니며, 제네릭을 선택한다고 해서 값이 반드시 복사되는 것도 아닙니다.
완전한 C# 프로그램:
using System;
interface ILabel { string Text(); }
class Local : ILabel { public string Text() { return "local"; } }
class Remote : ILabel { public string Text() { return "remote"; } }
class Program {
static void Main() {
ILabel[] labels = { new Local(), new Remote() };
foreach (var label in labels) Console.WriteLine(label.Text());
}
}완전한 Rust 프로그램:
trait Label { fn text(&self) -> &'static str; }
struct Local;
struct Remote;
impl Label for Local { fn text(&self) -> &'static str { "local" } }
impl Label for Remote { fn text(&self) -> &'static str { "remote" } }
fn main() {
let local = Local;
let remote = Remote;
let labels: [&dyn Label; 2] = [&local, &remote];
for label in &labels { println!("{}", label.text()); }
}챌린지
쉬움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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러