Menu
CoddyTech

トレイトオブジェクト

Coddyの「C開発者のためのRust」コースのレッスン 38/48。

ジェネリック型パラメーターは、インスタンス化ごとに具体的な型を選びます。一方、トレイトオブジェクトは、具体的な型が共通の振る舞いの背後に隠された値を参照します。&dyn Traitはそのような値を借用し、Box<dyn Trait>はヒープ上で所有します。ボックスのベクターには、同じトレイトを実装する異なる具体的な型を格納できます。呼び出しには動的ディスパッチが使われ、Cのコンテキストポインターとコールバックのテーブルを組み合わせる方法によく似ています。借用レシーバーと具体的な戻り値の型を持つシンプルなトレイトなら、この使い方ができます。ジェネリックメソッドがあると、そのトレイトをトレイトオブジェクトとして使えない場合があります。

C

#include <stdio.h>
struct Sensor { const void *context; int (*read)(const void *); };
struct Fixed { int value; };
struct Difference { int high; int low; };
int fixed_read(const void *p) { return ((const struct Fixed *)p)->value; }
int difference_read(const void *p) { const struct Difference *d = p; return d->high - d->low; }
int main(void) {
    struct Fixed f = {7}; struct Difference d = {9, 4};
    struct Sensor sensors[] = {{&f, fixed_read}, {&d, difference_read}};
    printf("%d\n", sensors[0].read(sensors[0].context) + sensors[1].read(sensors[1].context));
    return 0;
}

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);
}

ベクターの要素型は1つです。異なる具体的な実装型を同じベクターに格納できるのは、共通のトレイトオブジェクト型に変換した後だけです。

challenge icon

チャレンジ

簡単

adjuster::Adjusterを、apply(&self, value: i32) -> i32を含むものとして定義してください。offset::Offset { pub amount: i32 }に実装し、そのamountを加算するようにしてください。また、値とmaximumの小さい方を返すceiling::Ceiling { pub maximum: i32 }にも実装してください。pipeline::run(value: i32, steps: &[Box<dyn Adjuster>]) -> i32は、渡された各オブジェクトをスライスの順序どおりに1回ずつ適用し、各結果を次のオブジェクトに渡します。空のパイプラインは入力値を返します。solveは、初期整数の後にadd amountまたはcap maximumの完全なペアが続く形式を読み取ります。所有権を持つトレイトオブジェクトを作成し、最終値を返してください。すべての入力値と中間結果はi32に収まります。

必要な公開APIを実装し、exercise::solve(input: &str) -> Stringから結果を末尾の改行なしで返してください。編集可能なコードでは出力しないでください。ロックされたドライバーは必要なAPIを個別に検証し、標準入力をすべて読み取り、返されたテキストを末尾に改行を1つ付けて出力します。

コードは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));
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのRustのすべてのレッスン

自分で練習してみよう: Rustオンラインコンパイラ