我试图玩弄切片,但是一直不成功。
我将我的第一个问题简化为:
fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
let item = slice[index];
item
}
根据文档,我希望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
}
将类型强制转换为引用就可以解决问题。
为什么首先需要这些花招? 我做错了什么吗?