rust - 添加引用和数字值时了解(自动?)取消引用/强制

标签 rust

如何理解下面这段代码?我是 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 仅在它是接收者时发生,即方法调用中的“selffoo.bar() . x不是“ self ”论点,并且 +不是方法调用。所以这里没有自动取消引用。参见 What are Rust's exact auto-dereferencing rules?了解详情。

关于rust - 添加引用和数字值时了解(自动?)取消引用/强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360850/

相关文章:

rust - 如何证明类型中毒?

rust - 如何就地洗牌

opencv - OpenCV 的 Rust 绑定(bind)似乎缺少面部模块

rust - 在每次循环迭代中删除借位

vector - 以相同的方法在向量中查找并推送元素

rust - 为什么我们必须借用变量的类型而不是名称

iterator - 你如何实现一个迭代器,它的后继取决于术语的索引?

generics - 泛型结构的构造函数中出现 "Expected type parameter"错误

io - Rust 中的#[warn(unstable)] 是什么意思?

module - 当有 main.rs 和 lib.rs 时 Rust 模块混淆