简体   繁体   中英

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?

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: [] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM