【问题标题】:What's the idiomatic way to copy from a primitive type reference by value?按值从原始类型引用复制的惯用方法是什么?
【发布时间】:2014-10-30 07:26:06
【问题描述】:

考虑以下 sn-p:

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&amp;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()

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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    但是,原始类型(实际上,任何实现 Copy 特征的类型)都会在取消引用时被复制,所以你只需要这个:

    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,您无需手动取消引用它。

    【讨论】:

    • 现在,我发誓我是按照我之前读过的所有文档做的,编译器抱怨无法取消引用i,现在它编译了......好吧,我一定错过了什么.谢谢!
    【解决方案2】:

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

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

    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 &
    }
    

    【讨论】:

    • 虽然它以前没有编译过(因此提出了这个问题),但我确实学到了一些关于 &amp;x 解构的新东西。谢谢!
    【解决方案3】:

    如果您需要 &amp;mut 引用,请不要使用 iter。请改用iter_mut

    【讨论】:

    • 我为我糟糕的 sn-p 道歉。在这种情况下,current_items 包含 all_items 中项目的索引,因此我使用不可变引用 (&uint) 来访问可变引用。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 2010-09-27
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2016-12-02
    • 1970-01-01
    相关资源
    最近更新 更多