0

When I see this code everything is clear. We have a reference that we should dereference to manipulate and read data inside of it.

fn twice(x: &mut u8) {   
    *x = *x * 2;
}

But why does the following code compile?

fn twice(x: &u8) -> u8 {
    x * 2
}

Why doesn't Rust demand from me to dereference x here and requires it in the first example?

KindFrog
  • 358
  • 4
  • 17

1 Answers1

3

Rust has a Mul<u8> implementation for &u8. This means that you can multiply an &u8 and u8 to get a u8, with no dereferencing needed. However, for whatever reason, there's no instance for &mut u8, so the following will fail:

fn twice(x: &mut u8) -> u8 {
    x * 2
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55