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!");
}
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.
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