Negated vs. unnegated `&bool`

Why is this code valid?

fn main() {
    let v: bool = true;
    // with negation:
    if !&v {
        panic!();
    }
}

but this one isn't?

fn main() {
    let v: bool = true;
    // without negation:
    if &v {
        panic!();
    }
}

The latter results in:

error[E0308]: mismatched types
 --> not_neg.rs:3:8
  |
3 |     if &v {
  |        ^^ expected `bool`, found `&bool`
  |
help: consider removing the borrow
  |
3 -     if &v {
3 +     if v {
  |

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

with rustc 1.67.0-nightly (70f8737b2 2022-11-23).

It's because the ! operator is implemented by the standard library both for bool and for &bool.

1 Like

And Not for &bool has type Output = bool, which is what if needs.

You could write if !!&v if you really wanted to keep the reference in there. :slight_smile:

1 Like

I see, thanks. It just seemed a bit odd/inconsistent that one is valid, but not the other. Any insights on the purpose of implementing Not for &bool? Perhaps to avoid having to explicitly dereference?

Generic code, same as things like Add<&i32> for i32.

People might want to write code that works on Add<&T> to avoid copies if the thing they're adding is expensive to copy, and having these impls means that simple stuff like bool and i32 work in those cases too.

3 Likes

Got it, thanks!