简体   繁体   English

实现没有额外特征的特征方法

[英]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();
}

Playground 操场

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

相关问题 如何在不重复方法的情况下为结构实现多个特征? - How to implement multiple traits for a struct without repeating methods? 有什么方法可以在多个特征上实现一个特征? - Is there some way to implement a trait on multiple traits? Rustlings 练习 Traits2,在 Vec 上实现 Trait - Rustlings Exercise Traits2, Implement Trait on Vec 有没有办法表明impl特质类型也实现了其他特质? - Is there a way to signal that an impl trait type also implements additional traits? 如果两个特征都是为引用实现的,那么如何为实现特征A的所有类型实现特征B? - How can I implement trait B for all types that implement trait A if both traits are implemented for references? 我为另一个特征实现了一个特征,但不能从两个特征调用方法 - I implemented a trait for another trait but cannot call methods from both traits Rust 特质 - 如何在不消耗特质的情况下使用它? - Rust Traits - How can I use a trait without expending it? 为什么我要在特征上实现方法而不是作为特征的一部分? - Why would I implement methods on a trait instead of as part of the trait? 如何实现许多类似的特质方法? - How to implement many similar methods for trait? 如何为实现另一个特征的类型实现特征而不冲突的实现 - How to implement trait for types implementing another trait without conflicting implementations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM