0

New to rust. Would like to understand why this issue is occuring and how to fix. I don't think I can change the signature for the implementation of the trait method either which makes this more harder to fix.

use std::ops::{AddAssign};

pub struct ColumnVector {
    pub data: Vec<f32>
}

impl AddAssign for &ColumnVector {
    fn add_assign(&mut self, other: Self) {
        for (index, elem) in other.data.iter().enumerate() {
            self.data[index] += elem;
        }
    }
}

fn main() {
    
}
Brian Yeh
  • 3,119
  • 3
  • 26
  • 40
  • [Just remove the `&`?](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6b61135f49807088d9e44fa84efc8e42) is there something I'm missing here? You can't change a shared reference to a mutable one. – Jared Smith Mar 03 '23 at 16:56
  • Why are you implementing it on `&ColumnVector` instead of just `ColumnVector`? – kmdreko Mar 03 '23 at 16:56
  • @JaredSmith the location where this operator is used does not own the column vector. Actually I'm wondering if I impliment it for the ColumnVector straight up does it allow it to work on & and &mut? – Brian Yeh Mar 03 '23 at 17:07
  • @BrianYeh "the location where this operator is used does not own the column vector" not usually relevant. "if I impliment it for the ColumnVector straight up does it allow it to work on & and &mut?" Yes, usually those will be automatically dereferenced for you, see e.g. https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules – Jared Smith Mar 03 '23 at 18:06

1 Answers1

1

Using the & creates an immutable reference to ColumnVector and its fields, so you cannot get a mutable reference to update it.

You could do:


pub struct ColumnVector {
    pub data: Vec<f32>
}


impl AddAssign for &mut ColumnVector {
    fn add_assign(&mut self, other: Self) {
        for (index, elem) in other.data.iter().enumerate() {
            self.data[index] += elem;
        }
    }
}

fn main() {
    
}

if you needed the borrow, but you probably just want to remove the & entirely.

For context:

You can either have n-number of immutable borrows, or a single mutable one. There are ways around this (read about interior mutability) but generally you must have exclusive access to a variable to change it.

When you borrowed ColumnVector, you could not later edit the field because you did not own the data.

seve
  • 159
  • 12