Code Fix

上級E0782: trait objects must include the `dyn` keyword の原因と直し方 › パターン1

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

トレイトを直接型として使おうとすると、コンパイル時のサイズが確定できないためエラーになります。

 1  trait Shape {
 2      fn area(&self) -> f64;
 3  }
 4  struct Circle { r: f64 }
 5  impl Shape for Circle {
 6      fn area(&self) -> f64 { 3.14 * self.r * self.r }
 7  }
 8  fn main() {
 9      let shapes: Vec<Box<_________>> = vec![Box::new(Circle { r: 2.0 })];
                                ^
10      println!("{}", shapes[0].area());
11  }
error[E0782]: trait objects must include the `dyn` keyword

空欄を埋めて実行を通す

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

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

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

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

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