Poperton
Poperton

Reputation: 2127

How to make trait aliases?

I'm trying to give an alias to a function so I don't have to write its signature whenever I implement this trait:

type PhySend = Fn();
trait MyTrait {
    fn set_phy_send<F: PhySend>(callback: F);
}

But I get:

type aliases cannot be used as traits rustc(E0404)

So, is it impossible to give aliases to traits / function signatures? It'd be boring to write this signature every time I implement this trait.

Upvotes: 3

Views: 1379

Answers (1)

It's because aliases can be any type. Try to define a new trait instead.

trait your_function<T> : FnOnce() -> T {}

impl<T, U> your_function<T> for U where U: FnOnce() -> T {}

fn make_tea<F, T>(f: F) -> T
    where F: your_function<T>
{
    f()
}

fn main() {
    make_tea(|| String::new());
}

Upvotes: 10

Related Questions