A function returns transferring an ownership of heap data but there is no variable to receive it, when does heap memory get deallocated?

Hello eveyone, I'm new to Rust. The question I am going to ask might be very simple, but I dont know the answer.

In the Rust programming language book, there is an example of a function add_suffix that receives a mutable string and returns another string.

fn main() {
let first = String::from("Ferris");
let full = add_suffix(first);
println!("{full}");
}

fn add_suffix(mut name: String) -> String {
name.push_str(" Jr.");
name
}

"If a variable owns a box, when Rust deallocates the variable's frame, then Rust deallocates the box's heap memory"

Who deallocates the heap memory, lets say, when there is no variable like "full" to receive the return value of "add_suffix" function, hence there is no one owning the heap data ?

the return value has a temporary scope, which, in this case, ends at the end of the function call statement. when the temporary value is dropped, the memory is deallocated.

... the temporary scope of an expression is the smallest scope that contains the expression ...

see the full document:

https://doc.rust-lang.org/beta/reference/destructors.html#temporary-scopes

4 Likes

Thank you :slight_smile:

Tangential to your question, but it returns the same string. Note how String::push_str takes a &mut reference.

pub fn push_str(&mut self, string: &str)

Appends a given string slice onto the end of this String.

So,

//                      vvvvvv  Takes `String` by value
fn add_suffix(mut name: String) -> String {
    // Mutates it
    name.push_str(" Jr.");
    // Returns the *same* `String` by value
    // (OK the `push_str` may have involved a reallocation, but conceptually)
    name
}

Incidentally, read this pinned post to learn how to format your code blocks.

2 Likes