上級 › E0782: trait objects must include the `dyn` keyword の原因と直し方 › パターン4
E0782: trait objects must include the `dyn` keyword の原因と直し方
トレイトを直接型として使おうとすると、コンパイル時のサイズが確定できないためエラーになります。
1 trait Greeter { 2 fn hello(&self) -> String; 3 } 4 struct English; 5 impl Greeter for English { 6 fn hello(&self) -> String { String::from("hello") } 7 } 8 fn main() { 9 let greeters: Vec<Box<___________>> = vec![Box::new(English)]; ^ 10 println!("{}", greeters[0].hello()); 11 }
error[E0782]: trait objects must include the `dyn` keyword
空欄を埋めて実行を通す
Box<dyn Trait>にすることで、異なる具象型を同じVecにまとめて格納できます。
次の問題