R
Ownership & Borrowing
Rust syntax guide
Rust ownership system and borrowing
Ownership & Borrowing
Rust ownership system and borrowing
Rust ownership & borrowing (rust)
// Ownership basics
fn main() {
// Variable binding
let s1 = String::from("hello"); // s1 owns the string
let s2 = s1; // Ownership moves to s2, s1 is invalid
// println!("{}", s1); // This would cause a compile error
println!("s2: {}", s2); // s2 owns the string
// Borrowing
let s3 = String::from("world");
let len = calculate_length(&s3); // Borrow s3 (immutable reference)
println!("Length of '{}' is {}", s3, len); // s3 is still valid
// Mutable borrowing
let mut s4 = String::from("hello");
change_string(&mut s4); // Mutable borrow
println!("Changed: {}", s4);
// Multiple immutable borrows
let r1 = &s4;
let r2 = &s4;
// let r3 = &mut s4; // This would cause a compile error
println!("{} and {}", r1, r2);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn change_string(s: &mut String) {
s.push_str(" world");
}
// Ownership in functions
fn takes_ownership(some_string: String) {
println!("{}", some_string);
} // some_string goes out of scope and is dropped
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
} // some_integer goes out of scope, but nothing special happens
fn gives_ownership() -> String {
let some_string = String::from("yours");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string // Return ownership
}
Explanation
Rust ownership system ensures memory safety without garbage collection. Each value has one owner. References allow borrowing without transferring ownership.
Common Use Cases
- Systems programming
- Performance-critical code
- Embedded systems
- WebAssembly
Related Rust Syntax
Master Ownership & Borrowing in Rust
Understanding ownership & borrowing is fundamental to writing clean and efficient Rust code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using ownership & borrowing effectively in your Rust projects.
Key Takeaways
- Systems programming
- Performance-critical code
- Embedded systems