【发布时间】:2017-07-08 15:05:19
【问题描述】:
出于与代码组织相关的原因,我需要编译器接受以下(简化的)代码:
fn f() {
let mut vec = Vec::new();
let a = 0;
vec.push(&a);
let b = 0;
vec.push(&b);
// Use `vec`
}
编译器报错
error: `a` does not live long enough
--> src/main.rs:8:1
|
4 | vec.push(&a);
| - borrow occurs here
...
8 | }
| ^ `a` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
error: `b` does not live long enough
--> src/main.rs:8:1
|
6 | vec.push(&b);
| - borrow occurs here
7 | // Use `vec`
8 | }
| ^ `b` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
但是,我很难说服编译器将向量放在它引用的变量之前。 vec.clear() 不起作用,drop(vec) 也不起作用。 mem::transmute() 也不起作用(强制 vec 成为 'static)。
我找到的唯一解决方案是将引用转换为&'static _。还有其他方法吗?甚至可以在安全的 Rust 中编译它吗?
【问题讨论】:
标签: rust borrow-checker