ref_filter_map

Function ref_mut_filter_map

source
pub fn ref_mut_filter_map<T: ?Sized, U: ?Sized, F: FnOnce(&mut T) -> Option<&mut U>>(
    orig: RefMut<'_, T>,
    f: F,
) -> Option<RefMut<'_, U>>
Expand description

Make a new RefMut for a optional component of the borrowed data, e.g. an enum variant.

The RefCell is already mutably borrowed, so this cannot fail.

This is an associated function that needs to be used as RefMut::filter_map(...). A method would interfere with methods of the same name on the contents of a RefCell used through Deref.

ยงExample

use std::cell::{RefCell, RefMut};
use ref_filter_map::ref_mut_filter_map;

let c = RefCell::new(Ok(5));
{
    let b1: RefMut<Result<u32, ()>> = c.borrow_mut();
    let mut b2: RefMut<u32> = ref_mut_filter_map(b1, |o| o.as_mut().ok()).unwrap();
    assert_eq!(*b2, 5);
    *b2 = 42;
}
assert_eq!(*c.borrow(), Ok(42));