Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `sum += x` work the same as `sum += *x` for integer types? Is this an auto-dereference?

Tags:

rust

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;
    }
}
like image 761
J.C.M. Adona Avatar asked Nov 30 '25 08:11

J.C.M. Adona


1 Answers

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
like image 135
kmdreko Avatar answered Dec 01 '25 20:12

kmdreko