如何理解下面这段代码?我是Rust的新手,但有C/Haskell背景和一点点C++.我能找到的唯一参考是减轻强制.
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);
}
Run Code Online (Sandbox Code Playgroud)
这里没有自动deref或强制,i + x只是因为u32实现了Add<u32>和Add<&u32>.如果你查看文档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
Run Code Online (Sandbox Code Playgroud)
u32只实现AddAssign<u32>但不实现AddAssign<&u32>(这是一个bug和将在1.18或1.19中修复修复它导致回归,这意味着这个impl可能需要等待Rust 2.0),所以i += x是一个错误.
impl AddAssign<u32> for u32
//impl<'a> AddAssign<&'a u32> for u32 <-- is missing.
Run Code Online (Sandbox Code Playgroud)
为什么自动解除引用不会发生?- 只有当它是接收者时才会发生自动deref,即self方法调用中的" " foo.bar().x不是"自我"参数,+也不是方法调用.所以这里没有自动deref.请参阅什么是Rust的确切自动解除引用规则?细节.