Jiulia
Jiulia

Reputation: 323

Rust: cannot enqueue elements created inside scope, value does not live long enough

I'm new to Rust and I'm trying to create e program that does some recursive stuff on images. I believed i understood borrowing but unfortunately it seems i did not, I'm re-reding the manual, yes.

I can't really figure out a way to enqueue the elements of the positions array into queue without getting a "does not live long enough" error. What should i be using to achieve that? Is this pattern wrong in Rust?

pub struct Vec2 {
    pub x: u32,
    pub y: u32,
}

// ...

let p0 = Vec2{x:0,y:0};
let mut queue = VecDeque::from([&p0]);

let mut curr_node: &Vec2;

//!! "borrow later used here"
while queue.len() > 0 {
    curr_node = queue.pop_front().unwrap();

    let positions = [
        Vec2 {
            x: curr_node.x,
            y: curr_node.y,
        },
        Vec2 {
            x: curr_node.x + curr_size.x,
            y: curr_node.y,
        },
        Vec2 {
            x: curr_node.x,
            y: curr_node.y + curr_size.y,
        },
        Vec2 {
            x: curr_node.x + curr_size.x,
            y: curr_node.y + curr_size.y,
        }
    ];

    // some logic and stuff that will break the loop when needed

    for i in 0..4 {
        // the problem is here: "positions[_] does not live long enough"
        // "borrowed value does not live long enough"
        queue.push_back( &positions[i] );
    }
}

Upvotes: 0

Views: 43

Answers (1)

Aitch
Aitch

Reputation: 1697

Every value in Rust has to have an owner. positions in your code lives for one while-loop, so putting a reference into something that lives longer is not possible.

I don't know, what your code should do, but here is an example that works.

use std::collections::VecDeque;

#[derive(Debug)]
pub struct Vec2 {
    pub x: u32,
    pub y: u32,
}

fn main() {
    let p0 = Vec2 { x: 0, y: 0 };
    let mut queue = VecDeque::from([p0]);

    let curr_size = Vec2 { x: 10, y: 20 };

    while let Some(curr_node) = queue.pop_front() {
        // some logic and stuff that will break the loop when needed
        if queue.len() > 20 {
            break;
        }

        queue.push_back(Vec2 {
            x: curr_node.x,
            y: curr_node.y,
        });

        queue.push_back(Vec2 {
            x: curr_node.x + curr_size.x,
            y: curr_node.y,
        });

        queue.push_back(Vec2 {
            x: curr_node.x,
            y: curr_node.y + curr_size.y,
        });

        queue.push_back(Vec2 {
            x: curr_node.x + curr_size.x,
            y: curr_node.y + curr_size.y,
        });
    }

    println!("{:#?}", queue);
}

Upvotes: 1

Related Questions