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:
<details> <summary>Click here to reveal hints</summary>- 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!.
← PreviousNext →
use std::cell::RefCell;use std::rc::Rc;pub fn push<T>(data: Rc<RefCell<Vec<T>>>, element: T) {// 1. Finish the function}pub fn iterate_and_print_shared_data<T>(data: Rc<RefCell<Vec<T>>>) {// 2. Borrow the data and print each item}pub fn plus_one(data: Rc<RefCell<i32>>) {// 3. Finish the function}// Example usagepub fn main() {let shared_data = Rc::new(RefCell::new(vec![1, 2, 3]));// Updating shared datapush(Rc::clone(&shared_data), 4);push(Rc::clone(&shared_data), 5);// Iterating and printing shared dataprintln!("Shared Data:");iterate_and_print_shared_data(Rc::clone(&shared_data));let my_num = Rc::new(RefCell::new(5));plus_one(Rc::clone(&my_num));assert_eq!(*my_num.borrow(), 6, "Value was not incremented correctly.");}