Email or username:

Password:

Forgot your password?
Joshua Barretto

I want a Rust function with the following signature

fn specialise<T, U, R>(
in: T,
special: impl FnOnce(U) -> R,
fallback: impl FnOnce(T) -> R,
) -> R;

If T and U end up being the same type, it invokes `special` on `in`. Otherwise, it invokes `fallback` on `in`.

I believe this function would cover a good 80% of practical uses for specialisation, and be cleaner to use both for implementers and API users.

2 comments
Joshua Barretto

I implemented this function in my own language, Tao (it calls out to an intrinsic internally which causes the compiler to choose one of the two functions during monomorphisation). It works great. I'm currently using it to specialise the pretty-printing implementation for `Str` (which is just a type alias of `[Char]`) so that it doesn't print like a list (i.e: with brackets and commas between elements): github.com/zesterer/tao/blob/b

(I currently call it 'dispatch', although I'm going to change this)

I implemented this function in my own language, Tao (it calls out to an intrinsic internally which causes the compiler to choose one of the two functions during monomorphisation). It works great. I'm currently using it to specialise the pretty-printing implementation for `Str` (which is just a type alias of `[Char]`) so that it doesn't print like a list (i.e: with brackets and commas between elements): github.com/zesterer/tao/blob/b

Joshua Barretto

Having this in Rust would be so incredibly useful for so many things. Right now `std` bends over backwards with specialised helper traits to do things like not reallocating vectors where it doesn't need to, but I think almost all of these cases could be replaced with a simple call to such a function.

Go Up