0

I want to have a struct which contains a vector of points, and a vector of references (which connects 2 points together). I tried using the 'static lifetime but I get an error that points does not live long enough because its value is dropped when the program ends (at the closing brace of the main() function).

/// Contains a vec of points and references
struct Container {
    points: Vec<Point>,
    references: Vec<Reference>,
}

/// A single point in 2D space
struct Point(usize, usize);

/// Links 2 points together but only storing the reference, using 'static
struct Reference(&'static Point, &'static Point);

fn main() {
    let points = vec![
        Point(2, 1), Point(6, 4), Point(3, 2)
    ];

    let references = vec![
        Reference(&points[0], &points[1]), // error "borrowed value does not live long enough"
//                ^^^^^^^^^^  ^^^^^^^^^^
        Reference(&points[0], &points[2]),
    ];
    
    let container = Container{points, references};
}

I can't clone the points because I need to affect the original point. There might be another way store a list of links between 2 points but I'm struggling on figuring that out. Any help?

Cyclip
  • 11
  • 1
  • 2
  • 4
  • `points[0]` doesn't have static lifetime to begin with, so you wouldn't be able to store such a reference in `Reference` anyway. – cdhowie Aug 25 '22 at 18:15
  • While the linked answer explains why your approach doesn't work, here is a great explanation of how you'd make a graph (which is really what you're doing here) in Rust. https://www.youtube.com/watch?v=3DLrUNbKhjQ TL;DW use hashmaps to store nodes and their ids, and then define edges via the node ids, not references to the nodes. – cadolphs Aug 25 '22 at 23:16

0 Answers0