gpt4 book ai didi

rust - 为什么'static是impl的默认返回类型

转载 作者:行者123 更新时间:2023-12-05 05:35:25 26 4
gpt4 key购买 nike

我正在阅读 Jim Blandy、Jason Orendorff 和 Leonora F. S. Tindall 合着的《Programming Rust,第 2 版》一书。它说 'staticimpl 返回类型的默认值。

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 ... }
}

据我了解,return future 可能包含也可能不包含引用。它的生命周期可能不是'static

  1. 为什么 'staticimpl 返回类型的默认值?
  2. 进一步的问题是,任何没有显式生命周期注解的类型是否都被假定为'static

最佳答案

返回类型位置中 impl Trait 的默认设置是不捕获函数的生命周期,除非另有说明。因此,返回的类型不能引用它们,它唯一可以引用的其他生命周期是 'static

但是……

is any type without explicit lifetime annotation assumed to be 'static?

绝对不是! This is a common misconception , 但这是错误的。考虑:

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);
}

如果这是具体类型(不是泛型),那么我认为答案是肯定的。

关于rust - 为什么'static是impl的默认返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73523893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com