Welcome back to the 4th post of our 7 post Rust tutorial.
Rust’s ownership model is unique and ensures memory safety without garbage collection. Let’s simplify it.
Step 1: Understanding Ownership
In Rust, every value has a single owner. When ownership changes, the original owner can no longer use the value.
Example:
fn main() {
let s1 = String::from("hello"); // s1 owns the string
let s2 = s1; // Ownership moves to s2
// println!("{}", s1); // This won't work: s1 is no longer valid
println!("{}", s2); // s2 is the new owner
}
s1 is invalid after assigning it to s2.
This prevents double freeing of memory.
Step 2: Cloning Values
To keep the original value, use .clone().
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone(); // Makes a deep copy
println!("{}", s1); // Now s1 is still valid
println!("{}", s2);
}
Step 3: Borrowing with References
Borrowing allows you to use a value without taking ownership by passing a reference (&value).
Example
fn main() {
let s = String::from("hello");
let len = calculate_length(&s); // Borrow `s` with `&`
println!("The length of '{}' is {}.", s, len); // `s` is still valid
}
fn calculate_length(s: &String) -> usize { // `s` is a reference
s.len() // Access borrowed value
}
&s passes a reference to the function, so s retains ownership.
The function reads the value but can’t modify it.
Key Rule
Borrowing allows multiple immutable references but no mutable references at the same time.
Step 4: Mutable References
To modify a value, use &mut.
Example:
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s);
}
fn change(s: &mut String) {
s.push_str(", world"); // Append to the string
}
Only one mutable reference is allowed at a time to prevent conflicts.
Step 5: Rules of Ownership and Borrowing
Each value has one owner.
A value can only have one mutable reference or multiple immutable references, but not both.
References must always be valid.
Practice for Today
Write a program where a function calculates the square of a number using borrowing.
Modify a string inside a function using a mutable reference.
Try assigning a value to two mutable references and observe the compiler error.
🎉 That’s it for RUST BASICS 4! You’ve learned Borrowing and Ownership. In the next post, we’ll cover struct and enums in Rust.
Feel free to share your solutions or ask questions in the comments. Happy coding! 🦀
Check out the Rust Documentation for more details.
Let me know if anything feels unclear!
Top comments (0)