tmDDWCzr
tmDDWCzr

Reputation: 3

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:

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.

Upvotes: 0

Views: 77

Answers (1)

Jmb
Jmb

Reputation: 23453

You can add boxed directly to A with a default implementation so that structs won't need to implement it themselves:

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

Upvotes: 3

Related Questions