0

How can I return a String Vector in Rust? I tried:

fn test_vec() -> Vec<&str> {
    vec!("foo", "bar")
}

The compiler says something about lifetimes, but I'm not sure my problem is really about lifetimes:

src/main.rs:9:22: 9:26 error: missing lifetime specifier [E0106]

I'm a bit lost, I think I misunderstood (or forgot to learn) something.

1

1 Answer 1

6

A &str is not a String. It is a "string slice", meaning a kind of pointer into a String or something equivalent that is stored somewhere else. In your case you are using string literals (using quotes gives you string literals). String literals are of the type &'static str, because they are stored in the same place where the compiled code is stored and thus are available for the 'static lifetime, which means for (at least) the entire runtime of your program.

So the easy fix is to have your method return that specific type: &'static str.


The compiler cannot infer a lifetime for the returned reference, because your function does not take any arguments of reference type. The only way the compiler will infer a lifetime in a function's signature, is by assuming that if you are returning a reference, it needs to live shorter than the argument it's referring to. There's more information in The Book

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.