well…I’m working with some code that uses Rc<RefCell<SomeStruct>>
, and I’d like to understand its behavior better. Here’s what I know so far:
first, Rc
provides shared ownership, allowing multiple references to the same data…
and RefCell
provides interior mutability, allowing runtime-checked mutable borrows even behind immutable references…
i tried to run this code:
let vbaka = Rc::new(RefCell::new(40));
let mut mago = vbaka.borrow_mut();
*mago += 40;
println!("Modified value: {}", *mago);
let mago2 = vbaka.borrow();
println!("Original value: {}", *mago2);
i write this code on another file on src>
directory and call it on the main.rs
,
it’s prints the first value:
Modified value: 80
but it’s give an error, it’s panic:
thread ‘main’ panicked at srcsenarRcpointer.rs:28:23:
already mutably borrowed: BorrowError
note: run withRUST_BACKTRACE=1
environment variable to display a backtrace
error: process didn’t exit successfully:targetdebugdref.exe
(exit code: 101)
well, since combining both of Rc and RefCell gives you shared ownership, well, why i can’t borrow them twice? and mutate the value? and i’m also only once time mutably borrowed the vbaka
variable on mago
, the secound one ( which is mago2
was only an immutable references (borrow())
..
can anyone explain why this happend?
thank you all ))
dyadka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1