按值从原始类型引用复制的惯用方法是什么? [英] What's the idiomatic way to copy from a primitive type reference by value?

查看:22
本文介绍了按值从原始类型引用复制的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下片段:

fn example(current_items: Vec<usize>, mut all_items: Vec<i32>) {
    for i in current_items.iter() {
        let mut result = all_items.get_mut(i);
    }
}

编译器抱怨 i&mut usize 而不是 usize:

The compiler is complaining about i being &mut usize instead of usize:

error[E0277]: the trait bound `&usize: std::slice::SliceIndex<[()]>` is not satisfied
 --> src/lib.rs:3:36
  |
3 |         let mut result = all_items.get_mut(i);
  |                                    ^^^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `std::slice::SliceIndex<[()]>` is not implemented for `&usize`

我已经翻阅了文档,但我认为满足编译器的唯一方法是 i.clone().

I've dug through the docs but the only way I see to satisfy the compiler is i.clone().

我在这里肯定遗漏了一些明显的东西.按值从原始类型引用复制的惯用方法是什么?

I'm definitely missing something obvious here. What's the idiomatic way to copy from primitive type reference by value?

推荐答案

iter() on Vec 返回一个实现 Iterator<& 的迭代器T>,也就是说,这个迭代器将产生对向量的引用.这是最通用的行为,可以方便地使用不可复制的类型.

iter() on Vec<T> returns an iterator implementing Iterator<&T>, that is, this iterator will yield references into the vector. This is the most general behavior which allows convenient usage with non-copyable types.

然而,无论如何,原始类型(实际上,任何实现了 Copy trait 的类型)都会在取消引用时被复制,所以你只需要这个:

However, primitive types (actually, any types which implement Copy trait) will be copied upon dereference anyway, so you just need this:

for i in current_items.iter() {
    let mut result = all_items.get_mut(*i);
}

或者,您可以使用参考解构模式:

Alternatively, you can use reference destructuring pattern:

for &i in current_items.iter() {
    let mut result = all_items.get_mut(i);
}

现在 i 自动成为 usize 并且你不需要手动取消引用它.

Now i is usize automatically and you don't need to dereference it manually.

这篇关于按值从原始类型引用复制的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆