Rust:无法将在作用域内创建的元素排入队列,值的生存时间不够长



我是Rust的新手,我正在尝试创建一个对图像进行递归处理的程序。我相信我理解借款,但不幸的是,我似乎没有,我正在重新阅读手册,是的。

我真的想不出一种方法来将CCD_ 1数组的元素排入CCD_;寿命不够长";错误我应该用什么来实现这一点?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] );
}
}

Rust中的每个值都必须有一个所有者。代码中的positions只存在一个while循环,因此不可能将引用放入寿命更长的内容中。

我不知道你的代码应该做什么,但这里有一个有效的例子。

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);
}

相关内容

  • 没有找到相关文章

最新更新