use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
shared_map.borrow_mut().insert("africa", 92388);
shared_map.borrow_mut().insert("kyoto", 11837);
shared_map.borrow_mut().insert("piccadilly", 11826);
shared_map.borrow_mut().insert("marbles", 38);
}
从上例可看出,用了 RefCell 后,外面是 不可变引用 的情况,一样地可以修改被包裹的对象。
常用方法
.borrow()
不可变借用被包裹值。同时可存在多个不可变借用。
比如:
use std::cell::RefCell;
let c = RefCell::new(5);
let borrowed_five = c.borrow();
let borrowed_five2 = c.borrow();
下面的例子会崩溃:
use std::cell::RefCell;
use std::thread;
let result = thread::spawn(move || {
let c = RefCell::new(5);
let m = c.borrow_mut();
let b = c.borrow(); // this causes a panic
}).join();
assert!(result.is_err());
.borrow_mut()
可变借用被包裹值。同时只能有一个可变借用。
比如:
use std::cell::RefCell;
let c = RefCell::new(5);
let borrowed_five = c.borrow_mut();
下面的例子会崩溃:
use std::cell::RefCell;
use std::thread;
let result = thread::spawn(move || {
let c = RefCell::new(5);
let m = c.borrow();
let b = c.borrow_mut(); // this causes a panic
}).join();
assert!(result.is_err());
.into_inner()
取出包裹值。
use std::cell::RefCell;
let c = RefCell::new(5);
let five = c.into_inner();