How can I make a structure with internal references?

后端 未结 2 1175
长情又很酷
长情又很酷 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 10:42

    It is not possible to represent this concept in Rust with just references due to Rust’s memory safety—such an object could not be constructed without already existing. As long as nodes and adjacencies are stored separately, it’s OK, but as soon as you try to join them inside the same structure, it can’t be made to work thus.

    The alternatives are using reference counting (Rc if immutable is OK or Rc> with inner mutability) or using unsafe pointers (*const T or *mut T).

提交回复
热议问题