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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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. aminb.gitbooks.io/rust-for-c/content/arrays/index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.