rust - 如何实现递归节点结构?
问题描述
来自 Python,我想在 Rust 中实现一个 Node 结构,类似于下面的 Python 代码:
class Node:
def __init__(self, value: int, next_node: "Node"):
self.value: int = value
self.next: Node = next_node
def __repr__(self):
return f"Node(value: {self.value}, next: {self.next})"
if __name__ == "__main__":
a = Node(1, None)
b = Node(2, None)
# Link a.next with b
a.next = b
print(f"a now: {a}\n")
# Prints:
# a now: Node(value: 1, next: Node(value: 2, next: None))
# Change .value inside b
b.value = 3
print(f"a now: {a}")
print(f"b now: {b}\n")
# Prints:
# a now: Node(value: 1, next: Node(value: 3, next: None))
# b now: Node(value: 3, next: None)
# Change .value inside a.next
a.next.value = 4
print(f"a now: {a}")
print(f"b now: {b}")
# Prints:
# a now: Node(value: 1, next: Node(value: 4, next: None))
# b now: Node(value: 4, next: None)
到目前为止,我在 Rust 中的实现如下:
#[derive(Debug)]
#[derive(Clone)]
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
let mut a = Node { value: 1, next: None };
let mut b = Node { value: 2, next: None };
// Box and encapsulate a and b inside Option
let mut option_a = Some(Box::new(a));
let mut option_b = Some(Box::new(b));
// Link a.next with b
if let Some(ref mut a_unwrapped) = option_a {
a_unwrapped.next = option_b;
}
println!("a now: {:?}", option_a);
// Prints:
// a now: Some(Node { value: 1, next: Some(Node { value: 2, next: None }) })
}
但是,该行将a_unwrapped.next = option_b;
节点的option_b
内部移动a.next
而不是创建引用。现在我已经无法访问了option_b
。
与上述无关,可能可以使用以下方法更改节点内的值:
if let Some(ref mut b_unwrapped) = option_b {
b_unwrapped.value = 3;
// It is desired that a.next.value is now 3 as well
}
我想实现这个,因为我想在不使用 Rust 的数据结构和不使用关键字的情况下创建一个Queue
数据结构(可能还有二叉树),这只是个人挑战。Vec
unsafe
到目前为止,我能够使用此处Stack
描述的链表方法构建数据结构。
如您所见,我很难理解如何实现这一点。
在我看来,在 Rust 中拥有多个指向同一个对象的引用相当困难(因为数据竞争和竞争条件),或者我只是使用了错误的方法。
解决方案
推荐阅读
- json - Gatling 中的响应转换
- django-rest-framework - 如何在Django-MPTT中按父母对孩子进行分组
- azure - 无法连接到 ElasticSearch 托管服务
- css - 检查颜色 SASS 是黑色、白色还是灰色
- katalon-recorder - Katalon Recorder - 无法单击按钮
- java - 5 位数字逗号分隔值的正则表达式,例如 04700,04800,04900
- firebase - 我希望我的 firebase 实时数据库只接受比当前数据多 +1 的新数据。当前代码未按预期工作
- wavesplatform - 将美元价值分配给 Waves 智能资产代币
- windows - 在没有管理员权限的情况下以编程方式从 Rust 中检测 BitLocker
- react-native - 为什么 react-native webview 将一些 url 重定向到浏览器?