Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make trait aliases?

Tags:

rust

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.

like image 954
Guerlando OCs Avatar asked Oct 16 '25 18:10

Guerlando OCs


1 Answers

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

like image 142
Serge de Gosson de Varennes Avatar answered Oct 18 '25 13:10

Serge de Gosson de Varennes