CodeBlanks Logo Icon CodeBlanks

Return and ownership

See how returning a value transfers ownership back.

Returning and ownership

When a function returns a value, ownership moves to the caller. This lets values created inside a function be handed out safely:

fn yeni_liste() -> Vec<i32> {
    let v = vec![1, 2, 3];
    v                  // ownership goes to the caller, not dropped
}

fn ekle_unlem(mut s: String) -> String {
    s.push('!');
    s                  // the same String is handed back, no copy
}

Giving ownership and taking it back

To give a value to a function and get it back afterwards, you can return it, but it is clumsy:

fn uzunluk_ver(s: String) -> (String, usize) {
    let n = s.len();
    (s, n)
}
let (s, n) = uzunluk_ver(String::from("Rust"));

That's why Rust uses references for this: the function borrows the value and ownership never changes hands. The next group is about this.

Practice Transform and give back

Write fn ekle_unlem(mut s: String) -> String; it appends '!' and returns s. Call it with let s = ekle_unlem(String::from("Merhaba")); and print it.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn ekle_unlem(mut s: String) -> String {
    s.push('!');
    s
}

fn main() {
    let s = ekle_unlem(String::from("Merhaba"));
    println!("{}", s);
}

Expected output

Merhaba!

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Can a function return a reference (<code>&amp;String</code>) to its local <code>String</code>?

  • Yes, always
  • Only with mut
  • Only with clone
  • No; the value is dropped at the end of the function and the reference would dangle Correct answer

Explanation: The compiler rejects the dangling reference; the solution is to return the String itself and transfer ownership.

2 Give ownership back

Question
fn buyut(mut s: String) -> String {
    s.make_ascii_uppercase();
    ____
}
Answer
fn buyut(mut s: String) -> String {
    s.make_ascii_uppercase();
    s
}

Explanation: Writing s as the last expression moves the String's ownership to the caller.

3 Code and result

Term Meaning
-> String (local value) Ownership goes to the caller
-> &String (local value) Compile error
Returning (s, n) Giving ownership back
&s parametresi Borrowing

All lessons in Beginner