【发布时间】:2020-09-18 22:29:41
【问题描述】:
我有一个 trait 和一个 struct 来实现它。包裹在Arc中的struct可以调用trait的方法,但是Arc本身并没有实现:
use std::sync::Arc;
trait Foo{
fn bar(&self);
}
struct A;
impl Foo for A{
fn bar(&self){ }
}
fn test<A: Foo>(arc_a: Arc<A>){
let foo_obj: & dyn Foo = &arc_a; //the trait bound `std::sync::Arc<A>: Foo` is not satisfied
}
以下代码可以正常工作:
use std::sync::Arc;
trait Foo{
fn bar(&self);
}
struct A;
impl Foo for A{
fn bar(&self){ }
}
impl<A> Foo for Arc<A> //Manually implemented
where
A: Foo
{
fn bar(&self){ self.bar() }
}
fn test<A: Foo>(arc_a: Arc<A>){
let foo_obj: & dyn Foo = &arc_a;
}
有没有办法自动派生这种 trait 的实现?
【问题讨论】:
-
您的意思是引用
arc_a还是引用它后面的A?let foo_obj: &dyn Foo = &*arc_a;应该可以工作。但如果你的意思是另一回事,是的,你必须为Arc实现它,特别是如果这是你想要的行为。
标签: rust traits reference-counting