gpt4 book ai didi

rust - 如何为简单结构实现 `Index` 特征?

转载 作者:行者123 更新时间:2023-12-02 16:03:48 27 4
gpt4 key购买 nike

我正在尝试实现 Index一个简单特征的特征,我想将它与 usize 一起使用.我添加了 SliceIndex<[T], Output = T>所以我可以使用 T索引 slice里面A .

use std::ops::Index;
use std::slice::SliceIndex;

struct A <'a, T>{
slice: &'a [T]
}

impl<'a, T: Index<T, Output = T> + SliceIndex<[T], Output = T>> Index<T>
for A<'a, T>
{
type Output = T;

#[inline(always)]
fn index(&self, index: T) -> &Self::Output {
self.slice.index(index)
}
}

fn main() {
let mut aa: Vec<u64> = vec![0; 10];
let coefficient_iterable = A{slice: &aa};
println!("{}", coefficient_iterable[1usize]);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9564b39061cae3e19db14217c10b9d8a

但是我得到:

错误:

error[E0608]: cannot index into a value of type `A<'_, u64>`
--> src/main.rs:22:20
|
22 | println!("{}", coefficient_iterable[1usize]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0608`.
error: could not compile `playground` due to previous error

我不知道为什么,因为 usize工具 SliceIndex<[T]> .

最佳答案

需要 T两者都是 IndexSliceIndex没有意义,因为 Index描述了可索引容器的行为,而 SliceIndex是您可以放在通用索引类型上以使其更加灵活的界限。

您不想实现 Index<T>因为T这是切片中项目的类型,而不是索引的类型。对于您的 main 中的代码函数工作,你可以实现 Index<usize> , 但一般实现 Index<Idx> (其中 Idx: SliceIndex )提供了更大的灵 active ,因此您也可以使用范围。

use std::ops::Index;
use std::slice::SliceIndex;

struct A<'a, T> {
slice: &'a [T],
}

impl<'a, T, Idx> Index<Idx> for A<'a, T>
where
Idx: SliceIndex<[T], Output = T>,
{
type Output = T;

#[inline(always)]
fn index(&self, index: Idx) -> &Self::Output {
self.slice.index(index)
}
}

fn main() {
let aa: Vec<u64> = vec![0; 10];
let coefficient_iterable = A { slice: &aa };
assert_eq!(coefficient_iterable[1], 0);
}

关于rust - 如何为简单结构实现 `Index` 特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69950635/

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