Say I have a Pair<T>
wrapper that wraps two instance of a same type T
.
struct Pair<T> {
x: T,
y: T
}
Pair<T>
has a method called swap
that swaps between x
and y
. I want an implementation that if the type T
is "fast-swappable", that is, T
implements the trait FastSwap
, then the swap
implementation will call fast_swap
.
trait FastSwap<T> {
fn fast_swap(self: &mut Self, other: &mut T);
}
impl <T: FastSwap<T>> Pair<T> {
fn swap(&mut self) {
self.x.fast_swap(&mut self.y);
}
}
Also, if T
doesn't implement FastSwap
, there should be a fallback option using std::mem::swap
.
impl <T: !FastSwap<T>> Pair<T> {
fn swap(&mut self) {
std::mem::swap(&mut self.x, &mut self.y);
}
}
However, the Rust complier complains that I can't use !FastSwap
here. How to make the syntax correct? And also why !FastSwap
is forbidden here?