为什么我可以 return 引用本地文字而不是变量?

Why can I return a reference to a local literal but not a variable?

为什么这段代码可以编译?

fn get_iter() -> impl Iterator<Item = i32> {
    [1, 2, 3].iter().map(|&i| i)
}

fn main() {
    let _it = get_iter();
}

[1, 2, 3]是局部变量,iter()借用了。此代码不应编译,因为返回值包含对局部变量的引用。

在您的示例中,[1, 2, 3] 未被视为局部变量,而是被视为静态变量!

让我们看一下这段代码:

fn foo() -> &'static [i32] {
    &[1, 2, 3]
}

这有效!

前段时间,RFC 1414: Rvalue Static Promotion被合并:"Promote constexpr rvalues to values in static memory instead of stack slots"。这意味着基本上你写的所有文字都可以永远存在。因此,let _: &'static i32 = &42; 之类的东西也有效!

如果我们避免使用文字数组,我们会看到预期的错误:

fn bar() -> impl Iterator<Item = i32> {
    vec![1, 2, 3].iter().map(|&i| i)
}

这里出现“v 寿命不够长”的错误。

这不限于整数或数组;它广泛适用于任何仅由文字组成的文字:

fn promote_integer() -> &'static i32 {
    &42
}
fn promote_float() -> &'static f64 {
    &42.42
}
fn promote_str() -> &'static str {
    "Hello World!"
}
struct Foo(char);

fn promote_struct() -> &'static Foo {
    &Foo('x')
}

除了文字之外,这也适用于标准库中 极小 数量的函数,but these were likely a mistake. Deciding on if the result of arbitrary const functions can be automatically promoted to static is still an open topic.