Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rereference a mutable slice [duplicate]

I want to uptade a slice through a mutable reference.

While this does work with immutable slices:

fn shrink(value: &mut &[u8]) {
    *value = &value[0..2];
}

fn main() {
    let a = [0; 4];
    let mut a_slice: &[u8] = &a;
    shrink(&mut a_slice);
    println!("{:?}", a_slice);
}

It doesn't work with mutable ones:

fn shrink<'a: 'b, 'b>(value: &'a mut &'b mut [u8]) {
    *value = &mut value[0..2];
}

fn main() {
    let mut a = [0; 4];
    let mut a_slice: &mut [u8] = &mut a;
    shrink(&mut a_slice);
    println!("{:?}", a_slice);
}

Error message:

error[E0502]: cannot borrow `a_slice` as immutable because it is also borrowed as mutable
 --> src/main.rs:8:22
  |
7 |     shrink(&mut a_slice);
  |            ------------ mutable borrow occurs here
8 |     println!("{:?}", a_slice);
  |                      ^^^^^^^
  |                      |
  |                      immutable borrow occurs here
  |                      mutable borrow later used here

I know that there is a way to update the slice by directly returning a subslice.

But is there a way to make rereferencing a mutable slice through mutable reference possible?

The problem is similar to this one, but I can't figure what makes it so different, that proposed solution doesn't work.

like image 824
huh-hulk Avatar asked Oct 30 '25 02:10

huh-hulk


1 Answers

I don't know what the problem is with that code, but one option would be to return the updated slice directly:

fn shrink(value: &mut [u8]) -> &mut [u8] {
    &mut value[0..2]
}

fn main() {
    let mut a = [0; 4];
    let mut a_slice = &mut a[..];
    a_slice = shrink(a_slice);
    println!("{:?}", a_slice);
}

Rather than updating via the mutable reference, updating in the caller makes it clear that the old value of a_slice won't be used any more.

like image 181
Douglas Avatar answered Oct 31 '25 17:10

Douglas