Rc And RefCell Shared Ownership
Share one value across several owners with Rc clones and mutate it through RefCell, where borrow rules move to runtime checks.
Code
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Draft {
title: String,
views: RefCell<u32>,
}
fn main() {
// Rc:多个所有者共享(shared)同一份数据,clone 只增加引用计数
let draft = Rc::new(Draft {
title: "release notes".into(),
views: RefCell::new(0),
});
let reader = Rc::clone(&draft);
let writer = Rc::clone(&draft);
// RefCell 把借用检查移到运行时:多个不可变借用同时合法
println!("reader sees: {}", reader.views.borrow());
// borrow_mut 需要独占:不可变借用已结束,这里才能改
*writer.views.borrow_mut() += 3;
println!("after writer: {:?}", draft);
println!("strong count: {}", Rc::strong_count(&draft));
}What the code does
Rc And RefCell Shared Ownership reduces to the function main.
Applying it
Running the file prints labeled results such as reader sees:, after writer:, strong count: — each operation’s effect is visible in the output.
Statements that matter
let reader = Rc::clone(&draft);
let writer = Rc::clone(&draft);
Interactive Tools for This Topic
FAQ
- What does Rc And RefCell Shared Ownership print when run?
- Running the file directly is enough — expect labeled output lines such as `reader sees:`, `after writer:`, `strong count:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.