Ownership และ Borrowing
Rust References and Borrowing
Let a function use a value without taking it: & to read, &mut to change.
สิ่งที่คุณจะได้เรียนรู้
- & and &mut
- Borrowing in function calls
- Many readers or one writer
Borrow → what it allows
length(&message)read onlyadd_exclamation(&mut message)can change itlet first = &messagemany readers are fineUse a value without owning it
A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.
length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.
ประเด็นสำคัญ
- &value borrows for reading.
- &mut value borrows for changing.
- Many readers or one writer, never both.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn length(text: &str) -> usize {
text.len()
}
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut message = String::from("Borrow me");
let size = length(&message); // immutable borrow
println!("{message} has {size} bytes");
add_exclamation(&mut message); // mutable borrow
println!("{message}");
let first = &message;
let second = &message; // many readers are fine
println!("{first} {second}");
}
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- ย้ายเลขศูนย์ ย้ายเลขศูนย์ทั้งหมดไปไว้ท้ายสุด โดยลำดับของตัวเลขอื่นต้องคงเดิม ง่าย
- ทำให้อาเรย์ไม่ลดลง หาจำนวนครั้งที่ต้องเพิ่มค่าน้อยที่สุด เพื่อให้แต่ละค่ามากกว่าหรือเท่ากับค่าก่อนหน้า ง่าย