gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:43:02 25 4
gpt4 key购买 nike

我正在尝试尝试使用切片,但没有成功。

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

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
}

强制类型成为引用就可以了。

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

最佳答案

这是编译器为您所做的一些有用的人体工程学,目的是使代码看起来更漂亮。

Index 特征的返回值一个引用,但是编译器会自动为您插入一个取消引用当您使用加糖语法 []。大多数其他语言只会从数组中返回项目(复制它或返回对该对象的另一个引用,无论是否合适)。

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

let items = &[1u8, 2, 3, 4];

let a: u8 = items[0];
let a: u8 = *items.index(&0); // Equivalent of above

let b: &u8 = &items[0];
let b: &u8 = &*items.index(&0); // Equivalent of above

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

关于rust - 索引操作的返回类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com