问题描述
如何理解下面这段代码?我是 Rust 的新手,但有 C/Haskell 和一点 C++ 的背景知识.我能找到的唯一参考是 deref coercions.
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.
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);
}
推荐答案
这里没有 auto-deref 或 coercion,i + x
工作只是因为 u32
实现了两者Add
和 Add
.如果您查看 u32
的文档,你会发现以下四个特征实现:
There is no auto-deref or coercion here, i + x
works simply because u32
implements both Add<u32>
and Add<&u32>
. If you check the docs for u32
, you'll find the following four trait impls:
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
而不是 AddAssign
(这是一个错误 和 修复它导致回归,这意味着这个 impl 可能需要等待 Rust 2.0),所以 i += x
是一个错误.
u32
only implements AddAssign<u32>
but not AddAssign<&u32>
(this is a bug and fixing it causes regression which means this impl probably needs to wait for Rust 2.0), so i += x
is an error.
impl AddAssign<u32> for u32
//impl<'a> AddAssign<&'a u32> for u32 <-- is missing.
为什么自动解引用不会发生?— Auto-deref 仅在它是接收者时发生,即方法调用 foo.bar()
中的self
".x
不是self"参数,+
不是方法调用.所以这里没有自动取消引用.有关详细信息,请参阅 Rust 的确切自动取消引用规则是什么?.
Why does auto-dereferencing not happen? — Auto-deref only happens when it is a receiver i.e. the "self
" in a method call foo.bar()
. x
is not a "self" argument and +
is not a method call. So there's no auto-deref here. See What are Rust's exact auto-dereferencing rules? for detail.
这篇关于添加引用和数字值时了解(自动?)取消引用/强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!