How to return new data from a function as a reference without borrow checker issues?

Viewed 548

I'm writing a function that takes a reference to an integer and returns a vector of that integer times 2, 5 times. I think that'd look something like:

fn foo(x: &i64) -> Vec<&i64> {
    let mut v = vec![];
    for i in 0..5 {
        let q = x * 2;
        v.push(&q);
    }
    v
}

fn main() {
    let x = 5;
    let q = foo(&x);
    println!("{:?}", q);
}

The borrow checker goes nuts because I define a new variable, it's allocated on the stack, and goes out of scope at the end of the function.

What do I do? Certainly I can't go through life without writing functions that create new data! I'm aware there's Box, and Copy-type workarounds, but I'm interested in an idiomatic Rust solution.

I realize I could return a Vec<i64> but I think that'd run into the same issues? Mainly trying to come up with an "emblematic" problem for the general issue :)

1 Answers
Related