上級 › 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
空欄を埋めて実行を通す
トレイトを型として直接書くとサイズが不定になります。トレイトオブジェクトとして使うにはdynを付けます。
次の問題