4

I have a trait that is generic: trait Trait<T> and I want to create another trait that specifies the generics: type Alias = Trait<String>. This would allow impl Alias for T and not have to specify the type parameters. I tried a couple ways of doing this and haven't found any that works.

This is not a duplicate of Type alias for multiple traits or Aliasing trait with associated types because doing trait Alias: Trait<T> requires people to implement Trait<T> anyway. I want to offer a trait that hides the generics.

A clearer code sample:

trait DefaultEvents = Events<UserStruct, ChannelStruct, IrcStruct>;

struct MyHandler;

impl DefaultEvents for MyHandler {
    ...
}
Community
  • 1
  • 1
SBSTP
  • 3,479
  • 6
  • 30
  • 41
  • I've been there, and it doesn't quite answer my question. At least not to my understanding. I know about trait inheritance. Doing `trait Alias: Trait` doesn't do what I want, because it requires people to implement `Trait` anyway. I want to offer a trait that hides the generics. – SBSTP Apr 22 '16 at 16:47

1 Answers1

1

Here's my best suggestion, it's going to mean a bit more work on your part (with lots of manual trait inheritance), but it should achieve the user convenience that you want.

pub mod user_friendly {
    pub trait GivesNum<T> {
        fn get_num(&self) -> T;
    }

    pub trait GivesDouble {
        fn get_double(&self) -> f64;
    }

    impl<S> GivesNum<f64> for S where S: GivesDouble {
        fn get_num(&self) -> f64 { self.get_double() }
    }
}

// now your library's user needs to do less
use user_friendly::*;

struct MyStruct { num: f64 }

impl GivesDouble for MyStruct {
    fn get_double(&self) -> f64 { 2.0 * self.num }
}

fn main() {
    let s = MyStruct{ num: 5.0 };
    println!("MyStruct.get_num() = {}", s.get_num());
}

Try it on Rust Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ampron
  • 3,146
  • 2
  • 17
  • 13