Cannot return reference to temporary value in a flat_map

With the following simplified/abstracted version of my problem:

fn main() {
    let arr = vec![1., 2., 3., 4., 5., 6., 7., 8., 9.];
    let size = arr.len();

    let wave = |res: &Vec<f64>, step| {
        let size = res.len();
        let factor = size / (2 * step);
        res.chunks_exact(2)
            .collect::<Vec<_>>()
            .chunks_exact(factor)
            .flat_map(|arr| {
                arr.into_iter().flat_map(|x| {
                    &[(x[0] + x[1]), (x[0] - x[1])]
                })
            })
            .cloned()
            .collect::<Vec<_>>()
    };

    println!("{:?}", &arr);

    let mut res = arr.clone();
    for step in 1..size / 2 {
        res = wave(&res, step);
        println!("{:?}", &res);
    }
}

Got error:

error[E0515]: cannot return reference to temporary value
  --> src/main.rs:34:21
   |
34 |                     &[(x[0] + x[1]), (x[0] - x[1])]
   |                     ^------------------------------
   |                     ||
   |                     |temporary value created here
   |                     returns a reference to data owned by the current function

If remove .cloned() method, but appears next problem:

mismatched types:

error[E0308]: mismatched types
  --> src/main.rs:23:15
   |
23 |         res = wave(&res, step);
   |               ^^^^^^^^^^^^^^^^ expected f64, found &f64
   |
   = note: expected type `std::vec::Vec<f64>`
              found type `std::vec::Vec<&f64>`

Upvotes: 4

Views: 1215

Answers (1)

s810
s810

Reputation: 36

Returning a reference to an item outside of the function that it is created in directly violates Rust's ownership feature - see here.

When wanting to return data within a slice, use a Vec.

Solution below:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cc76fd3f1bc0aef7b7c2a60a35d40cc6

Upvotes: 2

Related Questions