上級 › E0782: trait objects must include the `dyn` keyword の原因と直し方 › パターン2
E0782: trait objects must include the `dyn` keyword の原因と直し方
トレイトを直接型として使おうとすると、コンパイル時のサイズが確定できないためエラーになります。
1 trait Animal { 2 fn speak(&self) -> String; 3 } 4 struct Dog; 5 impl Animal for Dog { 6 fn speak(&self) -> String { String::from("woof") } 7 } 8 fn main() { 9 let animals: Vec<Box<__________>> = vec![Box::new(Dog)]; ^ 10 println!("{}", animals[0].speak()); 11 }
error[E0782]: trait objects must include the `dyn` keyword
空欄を埋めて実行を通す
dynキーワードは「これは実行時に決まる動的な型のトレイトオブジェクトだ」とコンパイラに伝える印です。
次の問題