如何使用内部引用创建结构? [英] How can I make a structure with internal references?

查看:33
本文介绍了如何使用内部引用创建结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用邻接列表制作图表,但我不知道如何为邻接列表中的引用指定合适的生命周期.

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 trying to get at is the following:

struct Graph<T> {
    nodes : Vec<T>,
    adjacencies : Vec<Vec<&T>>
}

这将不起作用,因为引用类型缺少生命周期说明符.我想我可以对邻接使用索引,但我实际上对内部参考问题感兴趣,这只是表达该问题的工具.

This won't work because there is a lifetime specifier missing for the reference type. I suppose I could use indices for the adjacencies, but I'm actually interested in the internal reference problem, and this is just a vehicle to express that problem.

在我看来,这应该可以安全地进行,因为节点归对象所有.应该允许保留对这些节点的引用.

The way I see it, this should be possible to do safely, since the nodes are owned by the object. It should be allowed to keep references to those nodes around.

我说得对吗?如何在 Rust 中做到这一点?或者,如果我错了,我错过了什么?

Am I right? How can this be done in Rust? Or, if I'm wrong, what did I miss?

推荐答案

由于 Rust 的内存安全性,无法在 Rust 中仅用引用来表示这个概念——这样的对象不能在不存在的情况下构造.只要 nodesadjacencies 分开存储就可以,但是一旦你尝试将它们连接到同一个结构中,它就无法工作.

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.

替代方案是使用引用计数(Rc 如果不可变是 OK 或 Rc 具有内部可变性)或使用不安全的指针(*const T*mut T).

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

这篇关于如何使用内部引用创建结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆