Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.
I tried this code in Rust 0.6:
fn test<'r>(xs: &'r [&str]) -> &'r str {
return xs[0];
}
I think this type signature means: "test takes a borrowed pointer, with lifetime 'r, to a vector of borrowed pointers to strings, and returns a borrowed pointer to a string, also with lifetime 'r. But the compiler says:
refs.rs:2:8: 2:12 error: mismatched types: expected `&'r str` but found `&str` (lifetime mismatch)
refs.rs:2 return xs[0];
^~~~
refs.rs:1:39: 3:1 note: the lifetime &'r as defined on the block at 1:39...
refs.rs:1 fn test<'r>(xs: &'r [&str]) -> &'r str {
refs.rs:2 return xs[0];
refs.rs:3 }
refs.rs:1:39: 3:1 note: ...does not necessarily outlive the anonymous lifetime #1 defined on the block at 1:39
refs.rs:1 fn test<'r>(xs: &'r [&str]) -> &'r str {
refs.rs:2 return xs[0];
refs.rs:3 }
error: aborting due to previous error
This seems to imply that the pointers within the vector may not live as long as the (read-only) vector itself. Is this possible?
Is there some additional annotation I need to make to tell the compiler this is OK?
Likewise, what about vectors of owned pointers? e.g.
fn test<'r>(xs: &'r [~str]) -> &'r str {
return xs[0];
}
Again, I'd expect to be able to borrow a pointer to an element of the vector for at least as long as I've borrowed the whole list.
For context, my original problem was trying to extend a list of borrowed points with a list of owned pointers:
fn extend<'r>(xs: ~[&'r str], ys: &'r [~str]) -> ~[&'r str]
The plan was: create an exended list with all borrowed pointers, use it, then free the extended list, then free the original list of owned pointers, including the contained strings.