英文:
How should I get the add assign trait to work for a vector within a struct?
问题
New to rust. Would like to understand why this issue is occurring 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() {
}
英文:
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() {
}
答案1
得分: 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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论