Code Fix

上級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

空欄を埋めて実行を通す

広告
広告スロット(未設定)

E0782: trait objects must include the `dyn` keyword の原因と直し方

トレイトオブジェクトとして扱いたい場合は、dynキーワードを付けてBox<dyn Trait>や&dyn Traitのようにポインタ経由にする必要があります。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)