How can I make a structure with internal references?

后端 未结 2 1208
长情又很酷
长情又很酷 2021-01-20 10:02

I\'m trying to make a graph with adjacency lists, but I can\'t figure out how to specify an appropriate lifetime for the references in the adjacency list.

What I\'m

2条回答
  •  误落风尘
    2021-01-20 11:00

    I think there is an issue here. If we transpose this to C++:

    template 
    struct Graph {
        std::vector nodes;
        std::vector> adjacencies;
    };
    

    where adjacencies points into nodes, then one realizes that there is an issue: an operation on nodes that invalidates references (such as reallocation) will leave dangling pointers into adjacencies.

    I see at least two ways to fix this:

    • Use indexes in adjacencies, as those are stable
    • Use a level of indirection in nodes, so that the memory is pinned

    In Rust, this gives:

    struct Graph {
        nodes: Vec,
        adjacencies: Vec>,
    };
    
    struct Graph {
        nodes: Vec>>,
        adjacencies: Vec>>>,
    };
    

    Note: the RefCell is to allow mutating T despite it being aliased, by introducing a runtime check.

提交回复
热议问题