简体   繁体   中英

Why is 'static the default for impl as return types

I'm reading the book "Programming Rust, 2nd Edition" by Jim Blandy, Jason Orendorff, Leonora FS 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 .

  1. Why is 'static the default for impl return types?
  2. Further question, is any type without explicit lifetime annotation assumed to be 'static ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM