假设我有结构:
struct Vector {
data: [f32; 2]
}
实现 Index trait 很简单:
impl IndexMut<usize> for Vector {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.data[index]
}
}
我也有这个实现:
impl Vector {
fn x(&mut self) -> &mut T {
&mut self.data[0]
}
fn y....
}
技术上我可以做到,但每次我想实际设置 x() 的值时,我需要取消引用它:
*v.x() = 7
有效,但我希望 v.x() = 7
也有效。
当我尝试第二个时,我得到错误:
consider dereferencing here to assign to the mutably borrowed value: '*'
,我想这是有道理的,但它的发生很奇怪,因为 IndexMut 返回与我的 x() 函数返回相同的可变引用。
所以我的问题是:为什么 IndexMut trait 只做
v[0] = 7
,但我的函数需要在使用该值之前取消引用,我应该怎么做(如果可能的话)?