Ownership และ Borrowing
Rust Smart Pointers: Box and Rc
Put data on the heap with Box and share one value between several owners with Rc.
สิ่งที่คุณจะได้เรียนรู้
- Box<T> for recursive types
- Rc<T> for shared ownership
- Rc::strong_count
A list built with Box
- 1
Node(1)points to - 2
Node(2)points to - 3
Node(3)points to - 4
Endsum = 6
Pointers that own their data
A smart pointer owns the data it points to. Box<T> stores a value on the heap, which makes recursive types possible. Rc<T> lets several owners share one value by counting them.
List contains itself, so its size would be infinite without Box: a Box has a fixed size because it is only a pointer. Rc::clone does not copy the string, it adds an owner, and strong_count shows three owners. The value is freed when the last owner is gone.
ประเด็นสำคัญ
- Box has a fixed size, so a type can contain itself.
Rc::cloneadds an owner, it does not copy the data.- The value is freed when the last owner is gone.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
use std::rc::Rc;
enum List {
Node(i32, Box<List>),
End,
}
fn sum(list: &List) -> i32 {
match list {
List::Node(value, next) => value + sum(next),
List::End => 0,
}
}
fn main() {
let list = List::Node(1, Box::new(List::Node(2, Box::new(List::Node(3, Box::new(List::End))))));
println!("sum = {}", sum(&list));
let shared = Rc::new(String::from("shared config"));
let reader_a = Rc::clone(&shared);
let reader_b = Rc::clone(&shared);
println!("{reader_a} / {reader_b}");
println!("owners: {}", Rc::strong_count(&shared));
}
sum = 6
shared config / shared config
owners: 3ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- การดำเนินการกับลิงก์ลิสต์ จำลองลิงก์ลิสต์: เพิ่มที่ปลายทั้งสองด้าน ลบจากหัวหรือตามค่า และกลับลำดับ ง่าย