2

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.

Oliv
  • 17,610
  • 1
  • 29
  • 72
  • The duplicate applied to your problem: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5ed78f1d05a871c2639134280f4bf3b6). Your case is actually simpler than the one in the linked question, and there's no way the temporary empty slice can be observed from outside `func` (odds are good it gets optimized away entirely). – trent Sep 03 '20 at 18:37

0 Answers0