你不能。生命周期参数不允许您选择一个值的生命周期,它只允许您与编译器沟通两个或多个引用与同一内存“相关”并且预计共享相同的生命周期。
一个函数(比如你的new_int)可以通过两种方式分配内存:
- 本地分配给函数本身并在您从函数(堆栈)返回时销毁
- 动态地在所有函数(堆)共用的内存区域中
引用 (&) 是指向内存区域的指针。它可以指向本地堆栈或堆。由于动态分配在性能方面比在堆栈上写入要昂贵得多,因此 Rust 默认使用堆栈(您必须使用 Box 来执行动态分配)。
所以,简而言之,这就是您的代码非法的原因:
fn new_int<'a>() -> &'a isize {
let a: &'a isize = &5; // write 5 on the function's local stack
a // return a pointer to that area of memory
} // the function ends and its stack (where I wrote 5) is destroyed
// so the pointer I'm trying to return is no longer valid
你可以返回值
fn new_int() -> isize {
5
}
fn main() {
let a = new_int(); // the value 5 (not a pointer) is copied into a
}
或执行动态分配(这在 isize 的情况下是多余的,但如果您实际使用大型结构可能会有意义)
fn new_int() -> Box<isize> {
Box::new(5) // a Box allocates memory and writes in the heap
}
fn main() {
let a = *new_int();
}
或者,您可以在函数外部分配内存并在函数中对其进行变异。您通常不会为原始类型执行此操作,但在某些情况下(例如数据流)是有意义的:
// new_int does not return anything. Instead it mutates
// the old_int in place
fn new_int(old_int: &mut isize) {
*old_int = 5;
}
fn main() {
let mut a = 2; // memory for an int is allocated locally
// in main()
new_int(&mut a); // a mutable reference to that memory is passed
// to new_int, that overwrites it with another value
}
作为@dk mentions in the comment below,,在这种特定情况下(即您的函数总是返回 5 或其他一些静态已知值,而不是由函数动态计算的值),您还可以返回具有 'static 生命周期的引用:
fn new_int<'a>() -> &'a isize {
static FIVE: isize = 5;
&FIVE
}
你可以阅读更多关于'staticin the Rust Reference的信息。
从 Rust 1.21 开始,这个“静态提升”现在会自动为您执行,并且您的原始代码可以编译。它创建了 static FIVE 的等价物。