0

I'm trying to implement a mesh data structure in Rust, and I'm having trouble working out how to use lifetimes correctly. What I want is for the mesh to contain vertices, edges holding references to vertices, triangles holding references to edges, and tetrahedra holding references to triangles. The part where I am having trouble is that if a vertex is deleted, everything that contains it should be deleted. But the vertices all have different lifetimes, and I don't see any way to include that information in my struct definition. How can I get the behavior that I want?

struct Mesh<'vertex: 'edge, 'edge: 'triangle, 'triangle, T>
{
    vertices: std::vec::Vec<Vertex<T>>,
    edges: std::vec::Vec<Edge<'vertex, T>>,
    triangles: std::vec::Vec<Triangle<'vertex, 'edge, T>>,
    tetrahedra: std::vec::Vec<Tetrahedron<'vertex, 'edge, 'triangle, T>>,
}
Liam Clink
  • 189
  • 1
  • 11
  • You can’t use lifetimes for that. They’re something for the compiler to check statically. – Ry- Nov 06 '22 at 19:37
  • Ok, but when I have a struct that contains references, lifetimes are required, so what do I do with the lifetimes then? – Liam Clink Nov 06 '22 at 19:48
  • 1
    Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – jthulhu Nov 06 '22 at 20:27
  • @LiamClink I still think you misunderstand what lifetimes are. They are a mathematical tool for the compiler to prove that your objects exist as long as the reference exists. They only exist during compilation. The don't keep anything alive or have any runtime value. – Finomnis Nov 06 '22 at 22:13
  • To add to @BlackBean's reponse: You can use indices to achieve what you want. All of your data structures are `Vec`s, using indices for querying values is much simpler than references for your usecase, and it should be on par for performance. – Finomnis Nov 06 '22 at 22:14
  • Hmm, I think I understand what you mean. Problem is, I may end up referring to indices for vertices that do not exist anymore. This is why I wanted to use references. It sounds like this is essentially bypassing borrow checking. – Liam Clink Nov 06 '22 at 22:21
  • 1
    By using references you will not solve the problem, just make it more severe. Instead of accessing the wrong element, you would have UB. The borrow checker is preventing you from that. – Chayim Friedman Nov 06 '22 at 23:46

0 Answers0