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

This example demonstrates how to use borrowing in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Ownership Examples