0

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?

Zhiyao
  • 4,152
  • 2
  • 12
  • 21
  • @IbraheemAhmed Yes, partially. I would also like to know why I can't use `! Trait` here. Or maybe I'd better open another question to ask that? – Zhiyao Dec 10 '20 at 17:41
  • The reason you can't use `!Trait` which is known as [negative impls](https://doc.rust-lang.org/beta/unstable-book/language-features/negative-impls.html), is because the example you gave is not yet supported. – vallentin Dec 10 '20 at 17:51
  • @vallentin So, it's because the functionality has not yet been implemented, but not for some other theoretical reason, e.g. it will create an undecidable problem. Is my understanding correct? – Zhiyao Dec 10 '20 at 17:55
  • As far as I recall, "negative impls" or more specifically "negative bounds", are simply not supported yet. But what you're trying to do makes sense. However, you can augment it using specialization as Ibraheem linked to. – vallentin Dec 10 '20 at 18:05
  • 1
    With the specialization feature, you do not need an implementation for `Trait` and one for `!Trait`. Instead, you have a `default` implementation, and then a specialized implementation for `Trait`. – Ibraheem Ahmed Dec 10 '20 at 18:12

0 Answers0