首页 文章

通过值从原始类型引用复制的惯用方法是什么?

提问于
浏览
1

请考虑以下代码段:

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

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() .

我肯定错过了一些明显的东西 . 从值原始类型引用复制的惯用方法是什么?

3 回答

  • 6

    通过值从原始类型引用复制的惯用方法是什么?

    您需要使用 * 取消引用引用 .

    let my_usize: usize = 5;
    let ref_to_my_usize: &usize = &my_usize;
    let copy_of_my_usize: usize = *ref_to_my_usize;
    

    您也可以直接在循环中取消引用:

    for &x in myvec.iter() {
    //  ^-- note the &
    }
    
  • 1

    如果需要 &mut 参考,请不要使用 iter . 请改用iter_mut .

  • 6

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

    但是,原始类型(实际上,任何实现 Copy trait的类型)都将在取消引用时被复制,因此您只需要:

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

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

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

    现在 i 自动 usize ,您无需手动取消引用它 .

相关问题