【发布时间】: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 {
使结构/元组支持索引的最佳方法是什么?
【问题讨论】: