Interior Mutability
Rust provides powerful abstractions for managing memory safely and efficiently. One such abstraction is Rc (Reference Counting), which allows multiple ownership of data. When combined with RefCell, it unlocks the ability to mutate data through shared ownership safely at runtime.
In this challenge, you'll use Rc and RefCell together to explore the concept of Interior Mutability in Rust.
Your Task
Implement the following functions to demonstrate shared ownership and interior mutability:
-
push:- Accept an
Rc<RefCell<Vec<T>>>as input. - Append an element to the shared vector inside the
RefCell.
- Accept an
-
iterate_and_print_shared_data:- Take an
Rc<RefCell<Vec<T>>>as input. - Iterate through the vector and print each element.
- Take an
-
plus_one:- Accept an
Rc<RefCell<i32>as input. - Increment the value inside the
RefCellby one.
- Accept an
Requirements
- Use
Rcto share ownership of the vector. - Use
RefCellto allow interior mutability. - Avoid using unsafe code.
Hints
If you're stuck, here are some hints to help you solve the challenge:
Click here to reveal hints
- Use
Rc::cloneto share ownership of the vector. - Use
RefCell's.borrow_mut()for mutable access and.borrow()for immutable access. T: Displayis needed to format the output withprintln!.
No run yet
Press
Run to execute your code and see test results here.