rust - 为什么const变量可以与静态生命周期一起使用?

标签 rust

我一直在学习有效 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/

相关文章:

rust - "undefined reference to ` __stat_time64 '"在 musl 1.2.0 上交叉编译 Rust 项目时

types - 为什么索引显式类型的向量会因类型推断错误而失败?

rust - rust 究竟如何处理返回值

rust - 当存在嵌套的源目录时, 'use' 和 'mod' 如何工作?

rust-crypto 给出了许多 Unresolved 导入错误

github - Rustdoc 与 Travis 一起在 gh-pages 上

asynchronous - 特征绑定(bind) `tokio::net::tcp::stream::TcpStream: tokio_io::async_read::AsyncRead` 不满足

javascript - 为什么 Rust WASM 在计算素数时比 JavaScript 慢

rust - 有什么方法可以递归地展平元组吗?

rust - 如何找出可用的方法?