RRust By Example
beginnerOwnership

Ownership and Functions

How ownership transfers when passing values to functions.

Ownership and Functions

How ownership transfers when passing values to functions.

Difficulty

Beginner

Code

rust
fn take_ownership(s: String) {
    println!("took ownership of: {}", s);
}

fn give_back(s: String) -> String {
    println!("giving back: {}", s);
    s
}

fn main() {
    let s = String::from("hello");
    take_ownership(s);
    // s is no longer valid here

    let s2 = String::from("world");
    let s3 = give_back(s2);
    println!("got back: {}", s3);
}

Explanation

This example demonstrates how to use ownership and functions 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