Is it possible to return the link created inside the scope?

I have a pretty simple program:

fn f<'a>() -> &'a i32 {
    &1
}

fn main() {
    println!("{}", f());
}

It does not compile (some of the output has been excluded):

$ rustc test.rs
test.rs:2:6: 2:7 error: borrowed value does not live long enough
test.rs:2     &1

I understand why he is failing.

  • I do not know how to return the link created inside the function area. Is there any way to do this?
  • Why can not extend the service life for a single return?

EDIT: I changed the title as I suggested that the return type in the box help, but it is not (see answers).

+4
source share
3 answers

Rust RAII, , , , . -, . ( , , , ) . &str , "" ( ):

fn f<'a>() -> &'a str {
    "yo"
}
+2

. Box<T> unboxed T , . , , . , , . .

, , , . - , , , (.. -> i32 ) .

+2

Rust 1.21, rvalue static , .

, 1 , static, , 'static. de-sugared :

fn f<'a>() -> &'a i32 {
    static ONE: i32 = 1;
    &ONE
}

, structs:

struct Foo<'a> {
    x: i32,
    y: i32,
    p: Option<&'a Foo<'a>>
}

fn default_foo<'a>() -> &'a Foo<'a> {
    &Foo { x: 12, y: 90, p: None }
}

:

fn bad_foo<'a>(x: i32) -> &'a Foo<'a> {
    /* Doesn't compile as x isn't constant! */
    &Foo { x, y: 90, p: None }
}
+1

Source: https://habr.com/ru/post/1654930/


All Articles