Course contentsShow
← Rust
Lesson 232 of 1,9103. Borrowing and ReferencesFree lesson

Explicit vs Implicit Borrowing

Identify syntax shortcuts for creating references versus explicit borrow notation.

In this lesson, you will learn how Rust allows you to use shorthand syntax to create references without having to spell out every single technical detail.

The Nature of Borrowing Syntax

When we talk about "borrowing" in Rust, we are essentially creating a reference to data owned by someone else. So far, you have used the & operator to create these references. This is considered explicit borrowing because you are manually signaling to the compiler exactly where and how a reference should be created.

Implicit vs. Explicit

In most Rust code, the & operator is all you need. However, "implicit borrowing" happens when the compiler automatically creates a reference for you to satisfy a function signature or a method call.

Consider this example:

fn print_length(s: &String) {
    println!("{}", s.len());
}

fn main() {
    let my_string = String::from("Hello");

    // Explicit borrow:
    print_length(&my_string);
}

In the example above, &my_string is an explicit borrow. You are telling the compiler: "Take a reference to this variable."

However, Rust often uses Deref Coercion to make things easier. When you call a method on a type, Rust will automatically "borrow" the object for you if the method signature expects a reference.

let my_string = String::from("Rust");

// We don't have to write &my_string.len()
// The compiler implicitly borrows 'my_string' to call the method.
let len = my_string.len(); 

Why does this matter?

Explicit borrowing is your way of being clear and intentional. It ensures you know exactly when a variable is being accessed via a reference rather than being moved or consumed. Implicit borrowing is a quality-of-life feature that prevents your code from becoming cluttered with & symbols every time you call a method.

The most important thing to remember is that while the syntax might be implicit during method calls, the rules of borrowing (like the exclusive mutability constraints you learned earlier) still apply exactly the same way. Whether you write the & yourself or the compiler does it for you, the borrow checker is always watching to ensure your memory safety remains intact.

Key Takeaway: Explicit borrowing uses the & operator to signal your intent, while implicit borrowing allows the compiler to handle references automatically during method calls, keeping your code clean while upholding strict safety rules.