DEV Community

RealACJoshua
RealACJoshua

Posted on

🚀 Rust Basics 4: Ownership and Borrowing in Rust

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
}

Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

&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
}

Enter fullscreen mode Exit fullscreen mode

Only one mutable reference is allowed at a time to prevent conflicts.


Step 5: Rules of Ownership and Borrowing

  1. Each value has one owner.

  2. A value can only have one mutable reference or multiple immutable references, but not both.

  3. References must always be valid.


Practice for Today

  1. Write a program where a function calculates the square of a number using borrowing.

  2. Modify a string inside a function using a mutable reference.

  3. 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)