How to safely modify a mutable slice reference field?

Viewed 29

Let's consider this struct:

pub struct A<'a> {
    inner: &'a mut [u8],
}

I would like to modify inner so that it refer to a subslice of itself:

pub fn func (arg: &mut A) {
    arg.inner = &mut arg.inner[0..2];
}

But I get a lifetime mismatch error. I have tried this:

pub fn func <'x,'a> (arg: &'x mut A<'a>) where 'x:'a {
    arg.inner = &mut arg.inner[0..2];
}

this function compiles but... apparently if I use this function twice I get a cannot borrow twice error:

pub fn func2(arg: & mut [u8]){
    let mut a = A{inner: arg};
    func(&mut a);
    func(&mut a); //Error borrow twice
}

I'am a two week old rustacean, I'd like also to understand why the two version of func are wrong.

0 Answers
Related