Struct std::cell::RefMut 1.0.0[−][src]
pub struct RefMut<'b, T> where
T: 'b + ?Sized, { /* fields omitted */ }
Expand description
从 RefCell<T>
可变借来的值的包装器类型。
有关更多信息,请参见 模块级文档。
Implementations
为借用数据的一个组件 (例如一个枚举变体) 创建一个新的 RefMut
。
RefCell
已经是可变借用的,因此这不会失败。
这是一个关联函数,需要用作 RefMut::map(...)
。
方法会干扰通过 Deref
使用的 RefCell
内容中的同名方法。
Examples
use std::cell::{RefCell, RefMut};
let c = RefCell::new((5, 'b'));
{
let b1: RefMut<(u32, char)> = c.borrow_mut();
let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
assert_eq!(*b2, 5);
*b2 = 42;
}
assert_eq!(*c.borrow(), (42, 'b'));
Runpub fn filter_map<U, F>(
orig: RefMut<'b, T>,
f: F
) -> Result<RefMut<'b, U>, RefMut<'b, T>> where
F: FnOnce(&mut T) -> Option<&mut U>,
U: ?Sized,
pub fn filter_map<U, F>(
orig: RefMut<'b, T>,
f: F
) -> Result<RefMut<'b, U>, RefMut<'b, T>> where
F: FnOnce(&mut T) -> Option<&mut U>,
U: ?Sized,
为借用数据的可选组件制作新的 RefMut
。
如果闭包返回 None
,则原始守卫将作为 Err(..)
返回。
RefCell
已经是可变借用的,因此这不会失败。
这是一个关联函数,需要用作 RefMut::filter_map(...)
。
方法会干扰通过 Deref
使用的 RefCell
内容中的同名方法。
Examples
#![feature(cell_filter_map)]
use std::cell::{RefCell, RefMut};
let c = RefCell::new(vec![1, 2, 3]);
{
let b1: RefMut<Vec<u32>> = c.borrow_mut();
let mut b2: Result<RefMut<u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
if let Ok(mut b2) = b2 {
*b2 += 2;
}
}
assert_eq!(*c.borrow(), vec![1, 4, 3]);
Run将 RefMut
拆分为多个 RefMut
,以用于借用数据的不同组成部分。
底层 RefCell
将保持可变借用状态,直到两个返回的 RefMut 离开作用域。
RefCell
已经是可变借用的,因此这不会失败。
这是一个关联函数,需要用作 RefMut::map_split(...)
。
方法会干扰通过 Deref
使用的 RefCell
内容中的同名方法。
Examples
use std::cell::{RefCell, RefMut};
let cell = RefCell::new([1, 2, 3, 4]);
let borrow = cell.borrow_mut();
let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
assert_eq!(*begin, [1, 2]);
assert_eq!(*end, [3, 4]);
begin.copy_from_slice(&[4, 3]);
end.copy_from_slice(&[2, 1]);
Run转换为底层数据的可变引用。
底层 RefCell
不能再次借用,并且将始终显示为已经被可变借用,使得返回的引用成为内部的唯一引用。
这是一个关联函数,需要用作 RefMut::leak(...)
。
方法会干扰通过 Deref
使用的 RefCell
内容中的同名方法。
Examples
#![feature(cell_leak)]
use std::cell::{RefCell, RefMut};
let cell = RefCell::new(0);
let value = RefMut::leak(cell.borrow_mut());
assert_eq!(*value, 0);
*value = 1;
assert!(cell.try_borrow_mut().is_err());
Run