代码点读机 / Rust / RefCell

RefCell Rust · 常用类型

单线程下的运行时借用检查容器,把编译期借用规则检查推迟到运行时,违反会 panic。

怎么用

let 变量 = RefCell::new(值); 用 .borrow()/.borrow_mut(),用于单线程内部可变

小例子

use std::cell::RefCell;
let 列表 = RefCell::new(vec![1]);
列表.borrow_mut().push(2);
println!("{:?}", 列表.borrow());

运行结果

[1, 2]

提醒:不要在持有 borrow 时调用 borrow_mut,会 panic

官方文档:https://doc.rust-lang.org/std/cell/struct.RefCell.html

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Rust全部词条