3

I have an struct with a refence to an array of type T:

pub struct myStruct<'a, T> {
    pub data: &'a [T],
}

I want to modify one element of this array and check the result of an operation. for that I am trying to copy the array, modify the value and execute the operation:

pub fn check_value(&self, data: &T, position: usize) -> bool {
    if position >= self.data.len() {
        return false;
    }
    let array_temp = Box::new(self.data);
    array_temp[position] = *data;

    return mycheck(array_temp);
}

I am getting this error:

error[E0594]: cannot assign to `array_temp[_]` which is behind a `&` reference

I would like to know how to copy the array and modify the value or just modify directly the value in the original array (data) and restore the original value later.

Here you have a complete code to compile

pub struct MyStruct<'a, T> {
    pub data: &'a [T],
}

impl<'a, T> MyStruct<'a, T>
where
    T: Copy,
{
    fn mycheck(&self, myarray: &[T]) -> bool {
        if myarray.len() > 0 {
            return true;
        } else {
            return false;
        }
    }

    pub fn check_value(&self, data: &T, position: usize) -> bool {
        if position >= self.data.len() {
            return false;
        }
        let array_temp = Box::new(self.data);
        array_temp[position] = *data;
        return self.mycheck(&array_temp);
    }
}

fn main() {
    println!("Hello World!");
}
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
esguti
  • 234
  • 4
  • 11
  • Related: [How to convert from &\[u8\] to Vec?](https://stackoverflow.com/questions/47980023/how-to-convert-from-u8-to-vecu8) – trent Nov 27 '19 at 14:43

1 Answers1

4

You do not have an array (whose length is known), but you have a slice (whose length is not known at compile time). Thus, you must adjust to the dynamic length.

You probably want to use self.data.to_vec() instead of Box::new(self.data).

to_vec copies the values into a newly allocated vector having enough capacity.

phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • I see, the dynamic (run time) arrays (fixed lenght) are someway the "slices" in Rust. Coming from C/C++ this is not a clear conversion. https://aminb.gitbooks.io/rust-for-c/content/arrays/index.html – esguti Nov 28 '19 at 08:46