Sergey Zalizko
Sergey Zalizko

Reputation: 269

Incomprehensible behaivior of () -> &str function

I'm new in rust and don't understand one moment:

Pointer's Guide says: "You don't really should return pointers". I'm okay with that, but in my HelloWorld-like program I tried to return &str. I don't need boxed String, just &str to immediately print it. And I succeeded in this chalenge, but only partially.

So, question itself:

Why I can do

    fn foo(p: &[uint]) -> &str { "STRING" }

, but can't do

    fn foo(p: Vec<uint>) -> &str { "STRING" } //error: missing lifetime specifier [E0106]

, but still can do

    fn foo(p: Vec<uint>) -> &'static str { "STRING" }

What changes fact of switching from slice to Vec?

P.S. Sorry for my dummy english and dummy question. I think, I just don't get a point of rust's borrow-checher

Upvotes: 0

Views: 87

Answers (1)

Arjan
Arjan

Reputation: 21465

This is how lifetime specifiers are automatically added:

This:

fn foo(p: &[uint]) -> &str { "STRING" }

In the past you had to write it explicilty:

fn foo<'a>(p: &'a [uint]) -> &'a str { "STRING" }

These two are equivalent (but not really accurate since input p and returned str are not related). It works because 'static > 'a so is always valid for any lifetime.

The second example wont work because there is no input reference so no automatic lifetime parameters are added and the whole thing makes no sense (every reference needs a lifetime, explicit or implicit):

fn foo(p: Vec<uint>) -> &str { "STRING" }

As you already did you fix it by adding the lifetime to it:

fn foo(p: Vec<uint>) -> &'static str { "STRING" }

Upvotes: 7

Related Questions