Evan Conrad
Evan Conrad

Reputation: 4399

How do I empty a slice in a RefMut<&mut [u8]>?

If I wanted to "empty" a slice normally, I could do something like this:

let mut data: &[u8] = &[1, 2, 3];
data = &[];

But I'm using a library that returns a RefMut<&mut [u8]>, and if I try to reset it the same way:

let mut data: RefMut<&mut [u8]> = account.data.borrow_mut();
data = &[];

I get told I need:

expected struct `RefMut`, found `&[_; 0]`

I try something like this:

let mut data: RefMut<&mut [u8]> = account.data.borrow_mut();
let cleared: &mut [u8] = &mut [];
let c = RefCell::new(cleared);
data = c.borrow_mut();

But then c is dropped while still borrowed. Am I going about this the wrong way?

Upvotes: 0

Views: 354

Answers (1)

BallpointBen
BallpointBen

Reputation: 13820

You can use the dereference operator to write back to the RefCell.

let refcell: RefCell<&[u8]> = RefCell::new(&[1, 2, 3]);
{
    let mut data = refcell.borrow_mut();
    *data = &[];
    // or equivalently, *refcell.borrow_mut() = &[];
}
println!("{:?}", refcell); // RefCell { value: [] }

Upvotes: 6

Related Questions