Search code examples
rustownership

Need more explanation in the behaviour of Scope and Drop call in Rust in the context of Ownership


I'm a newbie to Rust and got little more curious to learn its ownership concepts. According to the Official Documentation the following is mentioned regarding concept of referencing:

Here is how you would define and use a calculate_length function that has a reference to an object as a parameter instead of taking ownership of the value:

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

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

The &s1 syntax lets us create a reference that refers to the value of s1 but does not own it. Because it does not own it, the value it points to will not be dropped when the reference stops being used.

So in the above scenario, the s1 is still accessible, and does not get out of scope untill the main function ends, and the drop is called only after the main function ends. But what if the value is passed to the calculate_length function like this?

let len = calculate_length(&String::from("hello"));

When is the drop called? Who is the owner of this String ? When the value of the referenced String instance is dropped? I'm little bit confused of this and would be thankful If i could get a simple effective explanation.


Solution

  • In other programming languages, such as C, something like &String::from("hello") would be prohibited because it's not clear that the value String::from("hello") has an address to start with.

    However, in Rust temporaries are dropped at the end of the statement they were created in (generally). So, in your case, it would be right after len has been assigned to.