gpt4 book ai didi

reference - 为什么我可以返回对局部文字的引用而不是变量?

转载 作者:行者123 更新时间:2023-11-29 08:32:08 24 4
gpt4 key购买 nike

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

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已合并:“将 constexpr 右值提升为静态内存中的值而不是堆栈槽中的值”。这意味着基本上你写的所有文字都可以永远存在。因此,像 let _: &'static i32 = &42; 这样的东西也可以工作!

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

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

这里我们得到“v does not live long enough”错误。

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

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 .决定任意 const 函数的结果是否可以自动提升为 static 仍然是 open topic .

关于reference - 为什么我可以返回对局部文字的引用而不是变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54278279/

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