简体   繁体   English

传递盒装特征作为参考

[英]Pass boxed trait as a reference

So I have a trait that I want to pass around and do some dynamic method dispatching on.所以我有一个特征,我想传递并执行一些动态方法调度。 I have one method that needs the trait as a boxed pointer, but it needs to call another method that uses a reference to the trait.我有一个方法需要特征作为装箱指针,但它需要调用另一个使用特征引用的方法。 So something like:所以像:

trait Foo {
    fn do_something(&self);
}

struct Bar;

impl Foo for Bar {
    fn do_something(&self) {}
}

fn foo_as_box(foo : Box<Foo>) {
    foo_as_ref(&foo);
}

fn foo_as_ref(foo : &Foo) {
    foo.do_something();
}

fn main() {
    let boxed_foo = box Bar as Box<Foo>;
    foo_as_box(boxed_foo);
} 

But, I get an error on this code但是,我在此代码上遇到错误

error: failed to find an implementation of trait Foo for Box Foo<no-bounds>

The compiler will convert Box<Foo> into &Foo as needed automatically.编译器会根据需要自动将Box<Foo>转换为&Foo You can just say你只能说

foo_as_ref(foo);

and it will work.它会起作用。

This doesn't necessarily work in more complex situations.这不一定适用于更复杂的情况。 Which is to say, the compiler can't always tell that you want that conversion.也就是说,编译器不能总是告诉你你想要那种转换。

Now that DST has been implemented, you can say &*foo to do the conversion.现在已经实现了DST ,您可以说&*foo进行转换。

In the past the only way to force it was a let -binding, as in在过去,强制它的唯一方法是let绑定,如

let ref_foo: &Foo = foo;

Of course, your use-case is simple enough that you don't need this.当然,您的用例很简单,您不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM