如何理解下面这段代码?我是 Rust 的新手,但有 C/Haskell 的背景和一点 C++。我能找到的唯一引用是 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);
}
最佳答案
这里没有自动取消引用或强制转换,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.
为什么自动取消引用不会发生? — Auto-deref 仅在它是接收者时发生,即方法调用中的“self
”foo.bar()
. x
不是“ self ”论点,并且 +
不是方法调用。所以这里没有自动取消引用。参见 What are Rust's exact auto-dereferencing rules?了解详情。
关于rust - 添加引用和数字值时了解(自动?)取消引用/强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360850/