I have following code and don't know how to get it working:
fn new_int<'a>() -> &'a isize {
&5
}
fn main() {
let x = new_int();
}
Or another attempt:
fn new_int<'a>() -> &'a isize {
let a: &'a isize = &5;
a
}
fn main() {
let x = new_int();
}
An alternative way of understanding why
can't work is as follows.
'a
is a lifetime parameter of the function; that is, it is the caller who chooses the actual value of this parameter, not the function itself. For example, the caller can choose'static
lifetime:However,
&5
can not have the'static
lifetime so the function is rejected.In other words, such declaration essentially says "I can give you a reference of any lifetime you want". Naturally, this is only valid if the reference returned from the function is of
'static
lifetime, which is the largest lifetime possible. That's what DK. is telling about, by the way.You can't. A lifetime parameter does not allow you to choose how long a value lives, it only allows you to communicate to the compiler that two or more references are "related" to the same memory and are expected to share the same lifetime.
A function (like
new_int
in your case) can allocate memory in two ways:A reference (
&
) is a pointer to an area of memory. It can point to the local stack, or to "the heap". Since dynamic allocations are much more expensive in terms of performance than writing on the stack, Rust uses the stack by default (you have to use a Box to perform a dynamic allocation).So, in a nutshell, this is why your code is illegal:
You can either return the value
or perform a dynamic allocation (which is overkill in case of an isize but might make sense if you're actually working with a big structure)
alternatively, you can allocate memory outside of the function and mutate it in the function. You don't typically do it for a primitive type, but it makes sense in some scenarios (e.g. streaming of data):
As @dk mentions in the comment below,, in this specific case (i.e. your function always returns 5 or some other statically known value, not something calculated dynamically by the function) you can also return a reference with a
'static
lifetime:You can read more about '
static
in the Rust Reference.As of Rust 1.21, this "static promotion" is now performed for you automatically and your original code compiles. It creates the equivalent of the
static FIVE
.