When I see this code everything is clear. We have a reference that we should dereference to manipulate 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 demands from me to dereference x here and requires it in the first example?
>Solution :
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
}