Both the non-commented and commented code result in the same sum value. I'm not sure what's happening here, but I'm expecting the compiler to throw an error on NOT using a dereference.
fn main() {
let a = vec![0, 1, 2, 3, 4];
let mut sum = 0;
for x in &a {
sum += *x;
// sum += x;
}
}
No, it is not a case of auto-dereferencing. The += operator (aka the trait AddAssign) is implemented for integer types (T) with both T and &T operands.
From the AddAssign docs:
impl AddAssign<i32> for i32
impl<'_> AddAssign<&'_ i32> for i32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With