【发布时间】:2021-02-02 15:09:45
【问题描述】:
为什么我不能对一个永不超出范围的值进行 'static 引用?
如果它永远不会超出范围,例如函数调用永远不会在主线程中返回,那么只要范围拥有它,数据就会保持有效,这将在程序的生命周期内。在这种情况下,我也应该能够在程序的生命周期内引用它,因为它在这段时间内保持有效,对吧?这是我的问题的一个例子:
fn noreturn() -> ! {
loop {}
}
fn main() {
// This value is never dropped or moved, and so it should last
// for 'static, right?
let not_dropped = 0usize;
// So I should be able to borrow it for 'static here, right?
let permanent_ref: &'static usize = ¬_dropped;
// This never returns, and so the value is never dropped
// and the data stays valid,
noreturn()
// .. but the compiler complains that not_dropped is dropped
// here even though it's never dropped. Why?
}
如果保证永远不会到达具有此值的范围的末尾,那么我应该能够永远持有对范围所拥有的有效值的引用,对吗?我在这里是否在概念上遗漏了什么?
【问题讨论】:
标签: rust reference lifetime borrow-checker borrowing