我一直在学习有效 Rust 项目 14 - The Static Lifetime 看来我不应该使用 const,如下所示:
const CANSWER: Item = Item { contents: 42 };
static SANSWER: Item = Item { contents: 42 };
pub fn the_answer() -> &'static Item {
&CANSWER
}
#[derive(Debug)]
pub struct Item {contents: u32 }
fn main() {
let c = the_answer();
println!("{c:?}");
}
它说这会出错,但为什么会编译?
我一直在寻找答案,但找不到。
最佳答案
这称为static promotion看起来它是在 2017 年添加的。本质上,当您引用 const
值时,它会创建一个 static
。之前,它会创建一个局部变量。
关于rust - 为什么const变量可以与静态生命周期一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75839662/