Reputation: 129
I'm reading the book "Programming Rust, 2nd Edition" by Jim Blandy, Jason Orendorff, Leonora F. S. Tindall. It says that 'static
is the default for impl
return types.
This version lets the async block capture host and path as owned String values, not &str references. Since the future owns all the data it needs to run, it is valid for the 'static lifetime. (We’ve spelled out + 'static in the signature shown earlier, but 'static is the default for -> impl return types, so omitting it would have no effect.)
fn cheapo_request<'a>(
host: &'a str,
port: u16,
path: &'a str,
) -> impl Future<Output = io::Result<String>> + 'static {
let host = host.to_string();
let path = path.to_string();
async move { ... use &*host, port, and path ... }
}
To my understanding, the return future may or may not contain references. Its lifetime may not be 'static
.
'static
the default for impl
return types?'static
?Upvotes: 4
Views: 381
Reputation: 71545
The default for impl Trait
in return type position is to not capture the lifetime of the function, unless specified otherwise. Because of that, the returned type cannot refer to them, and the only other lifetime it can refer to is 'static
.
But...
is any type without explicit lifetime annotation assumed to be
'static
?
Definitely not! This is a common misconception, but it is false. Consider:
fn takes_type_with_no_lifetime_annotation<T>(_v: T) {}
fn main() {
let s = String::new();
let has_non_static_lifetime = &s;
takes_type_with_no_lifetime_annotation::<&String>(has_non_static_lifetime);
}
If this is a concrete type (not generic), then I think the answer is yes.
Upvotes: 1