Adding two vector elements without copy or cloning them

⚓ Rust    📅 2025-08-17    👤 surdeus    👁️ 7      

surdeus

I have a case where the elements of a vector might be very large and I do not want to copy or clone them just to perform numerical operations.

Below is an example that demonstrates what I am trying to do:

[derive(Debug,Clone)]
struct ValVector {
    vec : Vec<f32> ,
}
impl ValVector {
    pub fn new( v : Vec<f32> ) -> Self {
        Self{ vec : v }
    }
}
impl std::ops::Add for ValVector {
    type Output = Self;

    fn add(self : Self, rhs : Self)  -> Self {
        let mut result = self.clone();
        for i in 0 .. self.vec.len() {
            result.vec[i] += rhs.vec[i];
        }
        result
    }
}

fn main() {
    //
    let va = ValVector::new( vec![ 1f32, 2f32 ] );
    let vb = ValVector::new( vec![ 3f32, 5f32 ] );
    let vv = vec![va, vb];
    let vc = vv[0] + vv[1];
    //
    println!("vc = {:?}", vc);
}


Here is the compiler error I get:

... snip ...
   Compiling package v0.1.0 (/home/bradbell/trash/rust/package)
error[E0507]: cannot move out of index of `Vec<ValVector>`
  --> src/main.rs:28:14
   |
28 |     let vc = vv[0] + vv[1];
   |              ^^^^^ move occurs because value has type `ValVector`, which does not implement the `Copy` trait
   |
help: consider cloning the value if the performance cost is acceptable
   |
28 |     let vc = vv[0].clone() + vv[1];
   | 
..., snip ...

4 posts - 3 participants

Read full topic

🏷️ Rust_feed