Understanding (automatic?) Deref/coercion when adding references and values of numbers

时间:2017-04-12 05:18:37

标签: rust

How to make sense of the following piece of code? I'm new to Rust but have background on C/Haskell and a little bit C++. The only reference I can find is to deref coercions将值传递给servlet时,用户界面不会出现。

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);
}

1 个答案:

答案 0 :(得分:9)

此处没有自动deref或强制,i + x只是因为u32同时实现了Add<u32>Add<&u32>。如果您选中the docs for u32,您会发现以下四个特征:

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

u32仅实施AddAssign<u32>但不AddAssign<&u32>this is a bug will be fixed in 1.18 or 1.19 修复causes regression这个impl可能需要等待Rust 2.0),所以i += x是一个错误。

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

为什么不进行自动解除引用? - 只有当它是接收者时才会发生自动deref,即方法调用self中的“foo.bar()”。 x不是“自我”参数,+不是方法调用。所以这里没有自动deref。有关详细信息,请参阅What are Rust's exact auto-dereferencing rules?