トレイトオブジェクト
Coddyの「Swift開発者のためのRust」コースのレッスン 38/48。
Swiftの存在型であるany Labelの値は、1つのプロトコルインターフェースの背後に、適合する異なる具象型を保持できます。Rustのトレイトオブジェクトは、選択したポインター表現を通じて実行時ディスパッチを提供し、Box<dyn Label>は所有権を伴う間接参照を追加します。Boxは割り当てを所有しますが、dynだけでは何も所有しません。一方、ジェネリックなT: Labelはインスタンス化ごとに具象型を扱い、動的ディスパッチを本質的に必要としません。インターフェースが似ていても、Swiftの存在型ストレージとRustのBoxのレイアウトは同一ではありません。トレイトオブジェクトとの互換性により、この方法で使用できるRustのトレイトメソッドの形式は制限されます。すべてのトレイト実装をボックス化するのではなく、設計上必要な場合に実行時の異種性を選びましょう。
単独で実行できる完全なSwiftプログラム:
protocol Label { func label() -> String }
struct Sun: Label { func label() -> String { "day" } }
struct Moon: Label { func label() -> String { "night" } }
let items: [any Label] = [Sun(), Moon()]
for item in items { print(item.label()) }
Swiftの出力:
day
night
単独で実行できる完全な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()); }
}Rustの出力:
day
night
チャレンジ
簡単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は、与えられた各オブジェクトをスライスの順序どおりに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));
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Swift開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ