내부 변경 가능성: RefCell, Cell
불변 참조를 통해 데이터를 변경 가능하게 안전하게 접근할 수 있도록 하는 `RefCell`과 `Cell`을 학습합니다.
내부 변경 가능성: RefCell, Cell은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Interior Mutability?
In Rust, the borrowing rules usually prevent you from having a mutable reference to data if you already have an immutable reference to it. This ensures data safety.
Interior mutability is a design pattern that allows you to mutate data even when you only have an immutable reference to it. It's like a controlled exception to Rust's usual rules, used in specific situations.
`Cell<T>`: For Copy Types
The Cell<T> type provides interior mutability for types that implement the Copy trait (like integers, booleans, characters). It works by replacing the value inside.
get(): Returns a copy of the value inside theCell.set(value): Replaces the value inside theCellwith a new one.
It's simple and efficient for small, copyable data.
Using `Cell` to Update Values
Here's a basic example of Cell. Notice how we can change the value inside the Cell even though the Cell itself is declared as immutable.
use std::cell::Cell;
fn main() {
let my_num = Cell::new(10);
println!("Initial value: {}", my_num.get());
my_num.set(20);
println!("Updated value: {}", my_num.get());
let x = &my_num;
x.set(30); // Still works via immutable reference!
println!("Via immutable ref: {}", my_num.get());
}`RefCell<T>`: For Non-Copy Types
When you need interior mutability for types that do not implement Copy (like String, Vec, or custom structs), you use RefCell<T>.
RefCell allows you to get mutable references to the inner data, but it enforces Rust's borrowing rules at runtime, not compile time.
`RefCell`'s Runtime Borrowing
RefCell provides methods that return smart pointers:
borrow(): Returns aRef(an immutable smart pointer). You can have multiple immutable borrows at once.borrow_mut(): Returns aRefMut(a mutable smart pointer). You can have only one mutable borrow at a time.
If you violate these rules at runtime, your program will panic!.
Using `RefCell` (Immutable Borrow)
Here, we use borrow() to get an immutable reference to the String inside the RefCell. We can print its content.
use std::cell::RefCell;
fn main() {
let my_string_cell = RefCell::new(String::from("Hello"));
let s1 = my_string_cell.borrow();
println!("Value: {}", *s1); // Dereference Ref to get String
let s2 = my_string_cell.borrow(); // Multiple immutable borrows are fine
println!("Another value: {}", *s2);
}Using `RefCell` (Mutable Borrow)
Now, let's get a mutable reference using borrow_mut(). This allows us to modify the String. Note that once s_mut is in scope, no other borrows (mutable or immutable) are allowed.
use std::cell::RefCell;
fn main() {
let my_string_cell = RefCell::new(String::from("World"));
{ // Scope for the mutable borrow
let mut s_mut = my_string_cell.borrow_mut();
s_mut.push_str(", Rust!");
}
// s_mut is out of scope here, so we can borrow again
let s_final = my_string_cell.borrow();
println!("Final value: {}", *s_final);
}The `RefCell` Runtime Panic
If you try to get a mutable borrow while another mutable borrow (or any immutable borrow) is active, RefCell will cause your program to panic! at runtime. This prevents data corruption.
Run this code to see it in action! It will crash with a "borrow already in use" error.
use std::cell::RefCell;
fn main() {
let my_value = RefCell::new(vec![1, 2, 3]);
let _first_mut_borrow = my_value.borrow_mut();
println!("First mutable borrow is active.");
// This line will cause a runtime panic!
// Try commenting it out to see the program run successfully.
let _second_mut_borrow = my_value.borrow_mut();
println!("This line will not be reached.");
}`Cell` vs. `RefCell` Summary
Choosing between Cell and RefCell depends on your data type and how you need to interact with it:
Cell<T>: Use for types that implementCopy. It replaces the entire value and is generally simpler and more performant.RefCell<T>: Use for types that do not implementCopy. It provides references to the inner data and enforces borrowing rules at runtime, allowing more complex mutations.
Quick Check: Cell or RefCell?
You have a struct that needs to store a mutable counter (u32) and a mutable list of names (Vec<String>), and both need to be updated through an immutable reference to the struct. Which interior mutability types would you use for each field?
Recap: Interior Mutability
You've learned about Rust's interior mutability pattern, which allows modifying data through an immutable reference in a controlled, safe way.
Cell<T>: ForCopytypes, replaces the inner value.RefCell<T>: For non-Copytypes, provides runtime-checked mutable/immutable references.- Violating
RefCell's rules leads to a runtime panic, ensuring safety.
These types are crucial for patterns like mock objects, circular references, or when a shared immutable reference needs to track internal state.
자주 묻는 질문
“내부 변경 가능성: RefCell, Cell” 강의는 무료인가요?
네 — “내부 변경 가능성: RefCell, Cell” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 3개의 강의가 포함되어 있습니다.
“내부 변경 가능성: RefCell, Cell”에서 뭘 배우나요?
불변 참조를 통해 데이터를 변경 가능하게 안전하게 접근할 수 있도록 하는 `RefCell`과 `Cell`을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“내부 변경 가능성: RefCell, Cell” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Box, Rc, Arc 스마트 포인터
- 내부 변경 가능성: RefCell, Cell
- 스레드로 두려움 없는 동시성 구현하기