Complete the code to create a new RefCell containing the value 5.
let value = std::cell::[1]::new(5);
The RefCell type allows mutable borrowing checked at runtime. Here, RefCell::new(5) creates a new RefCell holding the value 5.
Complete the code to borrow the value immutably from the RefCell.
let value = std::cell::RefCell::new(10); let borrowed = value.[1]();
The borrow() method immutably borrows the value inside the RefCell. It returns a smart pointer that enforces borrowing rules at runtime.
Fix the error in the code to mutably borrow the value inside the RefCell.
let cell = std::cell::RefCell::new(20); let mut_ref = cell.[1]();
The borrow_mut() method mutably borrows the value inside the RefCell. Using borrow() would only give an immutable borrow and cause a compile-time or runtime error if mutable access is needed.
Fill both blanks to create a RefCell, mutably borrow its value, and change it.
let cell = std::cell::[1]::new(30); let mut val = cell.[2](); *val = 40;
First, create a RefCell with RefCell::new(30). Then, mutably borrow the value with borrow_mut() to change it.
Fill all three blanks to create a RefCell, borrow it immutably, and print the value.
let cell = std::cell::[1]::new(50); let val = cell.[2](); println!("Value is: {}", *[3]);
Create a RefCell with RefCell::new(50). Then immutably borrow it with borrow(). Finally, dereference val to print the inner value.