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);
}
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.
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.
No, Dot (.) operator can't be overloaded. Doing so will cause an error.
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.
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:
IndexMut
trait)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With