struct - 如何向具有同类类型的结构/元组添加索引支持?

标签 struct types rust

我有兴趣添加对结构或元组索引的支持,即使它可以使用点语法 mytu​​ple.0 例如,我希望能够使用变量来访问索引,例如:mytu​​ple[i],

看文档,好像是支持的,eg:

use std::ops::Index;

struct Vector(f64, f64);

impl Index<usize> for Vector {
    type Output = f64;

    fn index(&self, _index: usize) -> f64 {
        match _index {
            0 => self.0,
            1 => self.1,
            _ => panic!("invalid index: {:?}", index)
        }
    }
}

fn main() {
    let v = Vector(5.0, 5.0);
    for i in 0..2 {
        println!("value {} at index {}\n", v[i], i);
    }
}

但是我得到这个错误:

src/main.rs:8:9: 14:10 error: method `index` has an incompatible type for trait:
 expected &-ptr,
    found f64 [E0053]
src/main.rs:8         fn index(&self, _index: usize) -> f64 {

使结构/元组支持索引的最佳方法是什么?

最佳答案

问题正是编译器告诉您的内容:您正在尝试更改Index 特征的定义。你不被允许那样做。再看定义:

pub trait Index<Idx> where Idx: ?Sized {
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}

具体看index的返回类型:&Output。如果Outputf64,那么index的结果必须&f64,不是如果,和,或但是。这是错误消息告诉您的内容:

method `index` has an incompatible type for trait: expected &-ptr, found f64

如果您要求编译器 explain that error code,您还会得到更详细的解释:

> rustc --explain E0053
The parameters of any trait method must match between a trait implementation
and the trait definition.

Here are a couple examples of this error:

```
trait Foo {
    fn foo(x: u16);
    fn bar(&self);
}

struct Bar;

impl Foo for Bar {
    // error, expected u16, found i16
    fn foo(x: i16) { }

    // error, values differ in mutability
    fn bar(&mut self) { }
}
```

解决方案是不改变特征并按要求返回一个借用的指针:

impl Index<usize> for Vector {
    type Output = f64;

    fn index(&self, index: usize) -> &f64 {
        match index {
            0 => &self.0,
            1 => &self.1,
            _ => panic!("invalid index: {:?}", index)
        }
    }
}

此外,为了抢占一个可能的后续问题:不,不能让索引返回一个值。

关于struct - 如何向具有同类类型的结构/元组添加索引支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38756951/

相关文章:

c - C 结构类型定义中无用的变量名

c - 使用多个小数组代替大数组

typescript - 条件类型的尾递归消除不起作用

angular - forkjoin 没有返回结果

rust - 无法创建 hyper::Client,因为编译器无法推断出足够的类型信息

pointers - 我应该如何决定何时更适合或不适合使用原始指针?

rust - .expect( format!() ) : expected `&str` , 找到结构 `String`

c - C 是否将结构填充初始化为零?

python - 确定变量的类型是 python 中的 NoneType

c - 如何设置结构体的字符串属性?