RRust By Example
beginnerOwnership

Borrowing

Use references to borrow values without taking ownership.

Borrowing

Use references to borrow values without taking ownership.

Difficulty

Beginner

Code

rust
fn calculate_length(s: &String) -> usize {
    s.len()
}

fn main() {
    let s = String::from("hello");
    let len = calculate_length(&s);
    println!(""{}" has length {}", s, len);
}

Explanation

References (&) borrow values without taking ownership. Multiple immutable borrows are allowed.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the ownership category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Ownership Examples