【问题标题】:How to add index support to a struct/tuples with homogeneous types?如何为具有同类类型的结构/元组添加索引支持?
【发布时间】:2016-08-04 01:06:18
【问题描述】:

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

查看文档,似乎这是支持的,例如:

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 {

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

【问题讨论】:

    标签: struct types rust


    【解决方案1】:

    问题正是编译器告诉你的:你试图改变Index trait 的定义。你不被允许这样做。再看定义:

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

    具体看index的返回类型:&amp;Output。如果Outputf64,那么index 的结果必须&amp;f64,没有ifs、ands 或buts。这就是错误消息告诉您的内容:

    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) { }
    }
    ```
    

    解决办法是不改变trait,按要求返回借来的指针:

    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)
            }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 1970-01-01
      • 2023-03-22
      • 2018-10-29
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多