John Estess
John Estess

Reputation: 636

Is there a way to overload the index assignment operator?

I can overload the [] operator with Index to return a ref, but I don't know if I have an overloaded operator to assign to the object.

This is what I want to do:

point[0] = 9.9;

This is what I can do so far (get a value):

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);
}

Upvotes: 18

Views: 10939

Answers (1)

Shepmaster
Shepmaster

Reputation: 430634

You are using Index, which says this in its documentation:

If a mutable value is requested, IndexMut is used instead.

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;
}

See also:

Upvotes: 20

Related Questions