Struct 如何向具有同构类型的结构/元组添加索引支持?
我有兴趣添加对结构或元组索引的支持,即使可以使用点语法Struct 如何向具有同构类型的结构/元组添加索引支持?,struct,types,rust,Struct,Types,Rust,我有兴趣添加对结构或元组索引的支持,即使可以使用点语法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 {
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);
}
}
使结构/元组支持索引的最佳方法是什么?问题正是编译器告诉您的:您正试图更改索引的定义。你不允许那样做。再看一下定义:
pub特征索引,其中Idx:?大小{
类型输出:?尺寸;
fn索引(&self,索引:Idx)->&self::输出;
}
具体来说,请查看索引的返回类型
:&输出
。如果输出
为f64
,则索引
的结果必须是&f64
,没有ifs、AND或buts。这是错误消息告诉您的:
method `index` has an incompatible type for trait: expected &-ptr, found f64
如果您要求编译器:
解决方案是不更改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)
}
}
}
impl向量索引{
类型输出=f64;
fn索引(&self,索引:usize)->&f64{
匹配索引{
0=>&self.0,
1=>&self.1,
_=>死机!(“无效索引:{:?}”,索引)
}
}
}
另外,为了避免可能的后续问题:不,您不能让索引返回值
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)
}
}
}