[英]How can a Rust trait object return another trait object?
如何在 Rust 中嘗試類似以下的操作?
builder 類是一個 trait 對象,它返回另一個 trait 對象(類型擦除),其中選擇的實現由我們正在使用的 builder trait 的特定對象定義。
trait Builder {
// I want this trait to return a trait object
fn commits(&self) -> dyn Commit;
fn finish(&self);
}
trait Commit {
}
struct FooBuilder {
}
struct FooCommit {
}
impl Builder for FooBuilder {
fn commits(&self) -> impl Commit {
FooCommit{ }
}
fn finish(&self) {
}
}
fn get_commits(b: &Builder) {
// trait object returns a trait
let c = b.commits();
}
fn main() {
let b = FooBuilder{};
get_commits(&b);
b.finish();
}
從 Rust 中的 trait 方法返回 trait 對象沒有問題:
trait Foo {
fn bar(&self) -> Box<dyn Bar>;
}
需要注意的一件事是您需要返回Box<dyn Bar>
,而不是dyn Bar
,因為在編譯時不知道dyn Bar
大小,這使得它無用。
當你實現這個特性時,簽名必須匹配,所以它應該返回Box<dyn Bar>
,而不是impl Bar
:
impl Foo for MyFoo {
fn bar(&self) -> Box<dyn Bar> {
Box::new(MyBar{})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.