前提・実現したいこと
Rustでトレイトオブジェクトを作るコンストラクタは、どのように記述するのでしょうか。
下記コードのStructAがOKで、StructBがNGである理由がなかなか理解できず…。
Self、オブジェクト安全性 などをキーワードにしてネットや書籍で調べたのですが、
コンストラクタの書き方を見つけられませんでした。
定番の書き方があれば教えて頂けないでしょうか。
該当のソースコード
Rust
1fn main() { 2 //この記述はOK 3 let x: Box<dyn TraitA> = Box::new( StructA {} ); 4 5 //このように記述したいが、コンパイルエラーになる 6 let y: Box<dyn TraitB> = Box::new( StructB::new() ); 7} 8 9struct StructA {} 10struct StructB {} 11 12trait TraitA {} 13trait TraitB { 14 fn new() -> Self; 15} 16 17impl TraitA for StructA {} 18impl TraitB for StructB { 19 fn new() -> Self { 20 Self {} 21 } 22}
発生している問題・エラーメッセージ
error[E0038]: the trait `TraitB` cannot be made into an object --> src/main.rs:6:12 | 6 | let y: Box<dyn TraitB> = Box::new( StructB::new() ); | ^^^^^^^^^^^^^^^ the trait `TraitB` cannot be made into an object ... 14 | fn new() -> Self; | --- associated function `new` has no `self` parameter error[E0038]: the trait `TraitB` cannot be made into an object --> src/main.rs:6:30 | 6 | let y: Box<dyn TraitB> = Box::new( StructB::new() ); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TraitB` cannot be made into an object ... 14 | fn new() -> Self; | --- associated function `new` has no `self` parameter | = note: required because of the requirements on the impl of `std::ops::CoerceUnsized<std::boxed::Box<dyn TraitB>>` for `std::boxed::Box<StructB>` = note: required by cast to type `std::boxed::Box<dyn TraitB>` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0038`.
補足
本質問は、以下の質問で頂いた回答から派生しました。
https://teratail.com/questions/244294?nli=5e5c3e7f-5198-4ba9-acc7-4de50a280215
補足情報(FW/ツールのバージョンなど)
OS: Windows10 + WSL1 + Ubuntu
Rust:1.41.0
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/03/04 12:49 編集