How to define methods for a type embedded in a struct that either implemented trait A or B?

Viewed 44

I have two traits and a struct:

pub trait A {}

pub trait B {}

struct S<T> { a: T }

I can define a method for S<T> only when T implements trait A and B:

impl<T: A + B> S<T> {
    pub fn do_something(&self) {
        println!("do_something");
    }
}

How can I define methods for S<T> when T implements trait A or B? I tried to write two impl but it doesn't work:

impl<T: A> S<T> {
    pub fn do_something_else(&self) {
        println!("do_something_else");
    }
}

impl<T: B> S<T> {
    pub fn do_something_else(&self) {
        println!("do_something_else");
    }
}

I got this error:

error[E0592]: duplicate definitions with name `do_something_else`
  --> src\main.rs:14:5
   |
14 |     pub fn do_something_else(&self) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definitions for `do_something_else`
...
20 |     pub fn do_something_else(&self) {
   |     ------------------------------- other definition for `do_something_else`
0 Answers
Related