Conditional function parameters dependent on trait bound

Sometimes I would like to change the type of a function parameter or struct parameter depending on whether it satisfies a trait bound or not.

unsafe fn myMultiThreadedFunction<T> (sharedResource: (if T: Sync <Arc<MyAtomicTrait<T>>> else Arc<Mutex<T>>) {
    // snip
}

This is obviously just example syntax. This might include some unsafe Rust, though, as it has a similar basis to unions, with types not being available at compile time.

Do you think this should be implemented?

«or not» means what you're asking for is specialization, so it brings in all the usual problems and known unsoundness of that feature.

1 Like

This would be possible with (full) specialization, e.g. with something like this:

trait SyncSwitch {
    type Shared;
}

default impl<T> SyncSwitch for T {
    type Shared = Arc<Mutex<T>>;
}

impl<T: Sync> SyncSwitch for T {
    type Shared = Arc<MyAtomicTrait<T>>;
}

unsafe fn myMultiThreadedFunction<T> (sharedResource: <T as SyncSwitch>::Shared) {
    // snip
}

But specialization is currently unstable and incomplete, so it isn't possible right now. And because of the soundness problems with specialization it won't become possible in the near future.

I see, thanks for the response!