如何从一个函数参数中推送一个项目到一个函数参数中的向量--不同的寿命问题。

问题描述 投票:1回答:1

我需要将一个项目推送到一个向量上,但项目和向量都是函数参数。但是 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

游戏场URL:- https:/play.rust-lang.org?version=stable&mode=debug&edition=2018&gist=e1f2d738a22795ae11aab01ad8d00d96。

rust lifetime
1个回答
1
投票

你需要添加一个寿命参数。

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)

© www.soinside.com 2019 - 2024. All rights reserved.