0
0
Rustprogramming~15 mins

RefCell overview in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
RefCell overview
📖 Scenario: Imagine you have a box that you want to share with your friends. Sometimes, you want to let one friend change what's inside the box, but other times, many friends can look inside without changing it. Rust's RefCell helps you do this safely at runtime.
🎯 Goal: You will create a simple Rust program using RefCell to hold a number. You will learn how to borrow it immutably (to read) and mutably (to change) safely.
📋 What You'll Learn
Create a RefCell holding an integer value
Borrow the value immutably to print it
Borrow the value mutably to change it
Print the changed value
💡 Why This Matters
🌍 Real World
RefCell is useful when you want to change data inside something that is normally immutable, like inside shared objects or GUI state.
💼 Career
Understanding RefCell helps you write safe Rust code that needs interior mutability, common in systems programming and application development.
Progress0 / 4 steps
1
Create a RefCell holding the number 10
Write a line to create a variable called value that is a RefCell holding the integer 10. Use std::cell::RefCell.
Rust
Hint

Use RefCell::new(10) to create the RefCell.

2
Borrow the value immutably to print it
Add a line to borrow value immutably using borrow() and print the number inside with println!. Use val as the variable name for the borrowed reference.
Rust
Hint

Use value.borrow() to get an immutable reference, then print with println!("Value is: {}", *val).

3
Borrow the value mutably to change it
Add code to borrow value mutably using borrow_mut() and change the number inside to 20. Use val_mut as the variable name for the mutable borrow.
Rust
Hint

Use value.borrow_mut() to get a mutable reference, then assign 20 to *val_mut.

4
Print the changed value
Add a line to borrow value immutably again and print the updated number with println!. Use val as the variable name for the borrowed reference.
Rust
Hint

Borrow immutably again with value.borrow() and print the new value.