Rust nổi tiếng với hệ thống ownership — cơ chế quản lý bộ nhớ tại compile-time mà không cần garbage collector.
Rust is famous for its ownership system — compile-time memory management without a garbage collector.
// Ba quy tắc của Ownership
// Three Rules of Ownership
- Mỗi giá trị có đúng một owner
- Tại một thời điểm chỉ có một owner duy nhất
- Khi owner ra khỏi scope, giá trị bị drop
- Each value has exactly one owner
- There can only be one owner at a time
- When the owner goes out of scope, the value is dropped
// Move Semantics
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // ERROR: s1 no longer valid
println!("{}", s2); // OK
rust
Rust invalidate biến gốc sau khi move, ngăn chặn hoàn toàn double-free bugs.
Rust invalidates the original variable after a move, completely preventing double-free bugs.
// Borrowing
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("Length of '{}' is {}", s1, len);
}
rust
// Mutable References
Rust cho phép tối đa một mutable reference tại một thời điểm:
Rust allows at most one mutable reference at a time:
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // ERROR: cannot borrow `s` as mutable more than once
r1.push_str(", world");
println!("{}", r1);
rust
// Lifetimes
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
rust
Lifetime annotation 'a nói với compiler: "output reference sống ít nhất bằng thời gian ngắn nhất của hai input references".
The lifetime annotation 'a tells the compiler: "the output reference lives at least as long as the shorter of the two input references".
"Ownership is Rust's most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector." — The Rust Book
// bình luận (đăng nhập GitHub) // comments (login with GitHub)