jadenPete
jadenPete

Reputation: 143

When can a function return a reference?

I was experimenting with Rust, and found an oddity that I cannot understand. Usually, the compiler prohibits a function from returning a reference without a static lifetime (e.g. String or &'static str, but never &str).

However, this code compiled and worked:

fn f(_: &Vec<u8>) -> &str {
    "Hello, world!"
}

Whereas this code did not:

fn f() -> &str {
    "Hello, world!"
}

Why does the first function work when it is returning a reference to a dropped value?

Upvotes: 0

Views: 129

Answers (1)

cy3er
cy3er

Reputation: 1699

It's the lifetime elision which doesn't work on functions without input parameters.

The first method is expanded to this:

fn f<'a>(_: &'a Vec<u8>) -> &'a str {

The second method is the 'ILLEGAL' example from the linked doc.

So you have to define it yourself:

fn f<'a>() -> &'a str {

...or static:

fn f() -> &'static str {

Upvotes: 4

Related Questions