[英]Implement methods for trait without additional traits
Looking for "blanket" implementation of the method(s) for trait.寻找特征方法的“一揽子”实现。
Let's say for a trait让我们说一个特征
pub trait A {
fn do_a(&self);
}
want to have boxed
method that wraps with box, without introducing any additional traits:想要用 box 包装的
boxed
方法,而不引入任何额外的特征:
fn boxed(self) -> Box<Self>;
I can have another trait to achieve that ( playground )我可以有另一个特质来实现这一点( 游乐场)
pub trait A {
fn do_a(&self);
}
pub trait Boxed {
fn boxed(self) -> Box<Self>;
}
impl<T> Boxed for T
where
T: A,
{
fn boxed(self) -> Box<Self> {
Box::new(self)
}
}
However, new trait Boxed
is required for that.但是,为此需要新特征
Boxed
。
You can add boxed
directly to A
with a default implementation so that structs won't need to implement it themselves:您可以使用默认实现将
boxed
直接添加到A
中,这样结构就不需要自己实现它了:
trait A {
fn do_a(&self);
fn boxed (self) -> Box<Self>
where Self: Sized
{
Box::new (self)
}
}
struct Foo{}
impl A for Foo {
fn do_a (&self) {
todo!();
}
// No need to redefine `boxed` here
}
fn main() {
let foo = Foo{};
let _object: Box<dyn A> = foo.boxed();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.