Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 962
John Estess Avatar asked Apr 01 '18 00:04

John Estess


People also ask

How do you overload the index operator?

In order to overload the operator of indexing the elements of the array [], the operator function operator[]() must be implemented in the class. There are 2 ways to implement the operator function operator[](). These variants differ in returning a value from an operator function.

Can we overload the operator?

These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.

Can you overload the dot operator?

No, Dot (.) operator can't be overloaded. Doing so will cause an error.

How do you overload an assignment operator in Python?

To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.


1 Answers

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:

  • Update value in mutable HashMap (why you cannot create a new value using the IndexMut trait)
like image 71
Shepmaster Avatar answered Oct 22 '22 06:10

Shepmaster