有没有办法重载索引赋值运算符?

时间:2018-04-01 00:46:29

标签: rust operator-overloading

我可以使用[]重载Index运算符以返回引用,但我不知道是否有重载运算符要分配给对象。

这就是我想要做的事情:

point[0] = 9.9;

这是我到目前为止所做的事情(得到一个值):

use std::ops::Index;

#[derive(Debug, Clone, Copy)]
pub struct Vec3 {
    e: [f32; 3],
}

impl Index<usize> for Vec3 {
    type Output = f32;
    fn index<'a>(&'a self, i: usize) -> &'a f32 {
        &self.e[i]
    }
}

fn main() {
    let point = Vec3 { e: [0.0, 1.0, 3.0] };
    let z = point[2];
    println!("{}", z);
}

1 个答案:

答案 0 :(得分:2)

您正在使用Index,在其文档中说明了这一点:

  

如果请求了可变值,则使用IndexMut代替。

use std::ops::{Index, IndexMut};

#[derive(Debug, Clone, Copy)]
pub struct Vec3 {
    e: [f32; 3],
}

impl Index<usize> for Vec3 {
    type Output = f32;
    fn index<'a>(&'a self, i: usize) -> &'a f32 {
        &self.e[i]
    }
}

impl IndexMut<usize> for Vec3 {
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut f32 {
        &mut self.e[i]
    }
}

fn main() {
    let mut point = Vec3 { e: [0.0, 1.0, 3.0] };
    point[0] = 99.9;
}

另见:

相关问题