Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading