Understanding (automatic?) Deref / coercion when adding links and number values

How to understand the following code fragment? I am new to Rust but have experience in C / Haskell and a bit of C ++. The only link I can find is deref coercions .

fn main() {
    let xs: [u32; 4] = [0, 1, 2, 3];
    let mut i: u32 = 0;
    for x in xs.iter() {
        if i > *x {     // It looks x is an iterator. Understood.            
            i = i + x;  // no error. (coerced)
                        //Quote: "Rust will do this as many times
                        //       as possible until the types match."
            i = i + *x; // no error (explicit deref)
            i += x;     // error about u32/&u32 mismatch. Why the magic failed?
            i += *x;    // no error (explicit deref)
        }
    }
    println!("{}", i);
}
+4
source share
1 answer

There is no auto-deference or coercion, it i + xworks simply because it u32implements both Add<u32>, and Add<&u32>. If you check the documents foru32 , you will find the following four signs of signs:

impl Add<u32> for u32
impl<'a> Add<u32> for &'a u32
impl<'a> Add<&'a u32> for u32
impl<'a, 'b> Add<&'a u32> for &'b u32

u32implements only AddAssign<u32>but not AddAssign<&u32>( this is a mistake and will be fixed in 1.18 or 1.19 , , , Rust 2.0), i += x .

impl AddAssign<u32> for u32
//impl<'a> AddAssign<&'a u32> for u32 <-- is missing.

? - Auto-deref , , .. "self" foo.bar(). x "self", + . , . . Rust's? .

+8

Source: https://habr.com/ru/post/1674626/


All Articles