我有兴趣添加对索引结构或元组的支持,即使它可能使用点语法mytuple.0
,例如,我希望能够使用变量来访问索引,例如:mytuple[i]
,
查看文档,似乎支持这一点,例如:
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 {
什么是使结构/元组支持索引的最佳方法?
答案 0 :(得分:3)
问题是完全编译器告诉你的内容:你正试图改变Index
特征的定义。你不允许那样做。再看一下定义:
pub trait Index<Idx> where Idx: ?Sized {
type Output: ?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
具体来说,请查看index
的返回类型:&Output
。如果Output
为f64
,那么index
的结果必须为&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) { }
}
```
解决方案是不更改特征并根据需要返回借用的指针:
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)
}
}
}
此外,要抢占可能的后续问题:否,您无法索引返回值。