索引操作的返回类型是什么?

时间:2015-01-10 17:40:01

标签: rust

我正在尝试,但却没有成功地玩切片。

我已将我的第一个问题缩减为:

fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
    let item = slice[index];
    item
}

鉴于documentation,我希望slice[index]的返回类型为参考:

pub trait Index<Index> {
    type Output;
    fn index(&'a self, index: &Index) -> &'a <Self as Index<Index>>::Output;
//                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

但是,编译器给出了一个错误:

  
error[E0308]: mismatched types
 --> src/main.rs:3:5
  |
3 |     item
  |     ^^^^ expected reference, found type parameter
  |
  = note: expected type `&'a T`
             found type `T`

我将其解释为item的类型与函数的返回类型不匹配(我仅为了调试目的引入item,从返回中拆分表达式求值)。

如果我将返回类型切换为T,这是item的类型,我会收到另一条错误消息:

  
error[E0508]: cannot move out of type `[T]`, a non-copy slice
 --> src/main.rs:2:16
  |
2 |     let item = slice[index];
  |                ^^^^^^^^^^^^
  |                |
  |                cannot move out of here
  |                help: consider using a reference instead: `&slice[index]`

经过修补,我发现了两个解决方法:

fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
    &slice[index]
//  ^
}

fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
    let ref item = slice[index];
//      ^~~
    item
}

强制该类型作为参考就可以了。

为什么这些恶作剧首先是必要的?我做错了吗?

2 个答案:

答案 0 :(得分:12)

这是一个有用的人体工程学设计,编译器为您做的,以使代码看起来更好。

Index trait 的返回值是引用,但是当您使用含糖语法时,编译器会自动为您插入解除引用<{1> }}。大多数其他语言只会从数组中返回该项(复制它或返回对该对象的另一个引用,无论什么是合适的)。

由于Rust的移动/复制语义的重要性,你不能总是复制一个值,所以在这些情况下,你通常会使用[]

&

请注意,索引值也会通过引用自动获取,类似于自动取消引用。

答案 1 :(得分:6)

不,你正在做的一切正确。虽然index()方法确实返回引用,但在索引操作中调用它时,其结果会自动解除引用。这样做是为了使索引更自然:在存在某种索引操作符的每种语言中(主要是C和C ++),它本身返回值,而不是对容器的引用。

为了获得对集合的引用,您必须明确地应用引用运算符(如在第一个“变通方法”中)或使用引用模式(如第二个)。