我需要将一个项目推送到一个向量上,但项目和向量都是函数参数。但是 item 和 vector 都是函数参数。
简单的代码重现:-
struct Point {
x: i32,
y: i32
}
fn main(){
let points: Vec<&Point> = vec!();
let start_point = Point {x: 1, y:2};
fn fill_points<F>(points: &mut Vec<&F>, point: &F ){
// Some conditions and loops
points.push(point);
}
fill_points(&mut points, & start_point);
}
错误:-
|
13 | fn fill_points<F>(points: &mut Vec<&F>, point: &F ){
| -- -- these two types are declared with different lifetimes...
14 | // Some conditions
15 | points.push(point);
| ^^^^^ ...but data from `point` flows into `points` here
你需要添加一个寿命参数。
struct Point {
x: i32,
y: i32,
}
fn main() {
let start_point = Point { x: 1, y: 2 };
let mut points: Vec<&Point> = vec![];
fn fill_points<'a, F>(points: &mut Vec<&'a F>, point: &'a F) {
// Some conditions
points.push(point);
}
fill_points(&mut points, &start_point);
}
(代码简化为基于 评论 来自@Stargateur)