-1

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.

Akash R
  • 46
  • 1
  • 7
  • 1
    Note that [you should take `&str`, not `&String`](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-string-vec-or-box-as-a-function). – Chayim Friedman Aug 31 '23 at 06:31
  • I actually wanted to know how it works behind the scenes, since they have mentioned as follows in their docs: >Because it does not own it, the value it points to will not be dropped when the reference stops being used. – Akash R Aug 31 '23 at 07:18
  • @ChayimFriedman, I take your suggestion. But im searching for a convincing answer for what happens if such values are passed in, in the context of Ownership, scope and drop function call – Akash R Aug 31 '23 at 07:20

1 Answers1

4

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.

jthulhu
  • 7,223
  • 2
  • 16
  • 33