I came across some snippets about "numeric" operations +
, &
etc (std::ops - Rust) and find out Rust has the weird treatment of the borrowed reference type.
For example, the code below runs correctly, but the commented two statements are disallowed.
fn main() {
let mut arr = [1u8, 2, 3, 4];
{
let pos: &u8 = unsafe { arr.get_unchecked(2) };
let v: u8 = pos + &1u8;
let w: u8 = &2u8 + pos;
println!("v={}, w={}", v, w);
}
{
let pos: &mut u8 = unsafe { arr.get_unchecked_mut(2) };
// let v = pos + 1u8;
// *pos += &1u8;
let v: u8 = *pos + &1u8;
let w: u8 = &2u8 + *pos;
println!("v={}, w={}", v, w);
}
}
Also here Rust Playground
My question is that why Rust allows operations between "&T
op
T", "&T
op
&T
", and "T
op
&T
" (and the resulting type is T
) where T is a primitive numeric type, but doesn't allow "&mut T
op
T" etc.
This to me seems rather unintuitive and I would expect that Rust requires programmers to be more explicit. Is there a particular reason that forces Rust to behave like this?