【发布时间】:2015-03-08 20:55:29
【问题描述】:
我正在尝试玩切片,但非常不成功。
我已将我的第一个问题简化为:
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
}
强制类型为引用就可以了。
为什么首先需要这些恶作剧?我做错了什么吗?
【问题讨论】:
标签: rust