Omegon
Omegon

Reputation: 461

Why can't I return a link to a string from a function, but can I slice?

I'm reading the initial Rust guide. And there it is shown that it is impossible to return a reference to a string from a function.

fn dangle() -> &String { // dangle returns a reference to a String

    let s = String::from("hello"); // s is a new String

    &s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
  // Danger!

But I am confused by the example from the next chapter , where the link to slice is returned from the function:

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

I understand why it is impossible to return a link to a string from a function, but why is it possible to return a link to a slice in this way? because the string itself is passed by reference, or is that not the reason? I'm a beginner and I'll be glad if someone helps me understand what's going on here.

Upvotes: 2

Views: 91

Answers (1)

tadman
tadman

Reputation: 211590

In the first case you're returning a reference to a locally scoped, temporary variable. This is not fine, that value will be dropped, as noted, which invalidates any references.

In the second case you're returning a reference to data supplied in the argument with a lifetime outside of the function, so it's fine. The lifetime of the return value is the lifetime of the caller's argument, whatever that is.

Upvotes: 6

Related Questions