我正在努力,非常不成功地玩切片。
我把我的第一个问题减少到:
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
}
强制该类型作为参考就可以了。
为什么这些恶作剧首先是必要的? 难道我做错了什么?