如何在改变数据时保持不可变借用?

  • 本文关键字:不可变 改变 数据 rust
  • 更新时间 :
  • 英文 :


我正在尝试为我的抽象节点系统写一个渲染器。

每个节点在一个电路上,它看起来像:

struct Circuit<'a> {
nodes: Vec<Node>,
connections: Vec<Connection<'a>>,
}

每个节点包含一些任意数据,并且连接这两个节点。

struct Connection<'a> {
from: &'a Node,
to: &'a Node,
}

在一个实例中,我试图对Circuit.nodes进行可变迭代并更改一些数据,同时仍然保持对Connections内部Node的引用。我希望Connection引用仍然保持对相同Node结构的引用,但指向可变借用后更新的数据。

但是有了这个设置,我得到一个cannot borrow 'circuit.nodes' as mutable because it is also borrowed as immutable错误。

我试过使用RefCellMutex,但没有成功。我找不到能很好地解释这个问题的资源。

也许你想包装你的节点在Rc(或Arc,如果在多线程环境中),这样,连接和电路就可以在节点上共享所有权

use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let a = Rc::new(RefCell::new(Node { data: "a".into() }));
let b = Rc::new(RefCell::new(Node { data: "b".into() }));
let conn = Connection {
from: a.clone(),
to: b.clone(),
};
let cir = Circuit {
nodes: vec![a.clone(), b.clone()],
connections: vec![conn],
};
}
#[derive(Debug)]
struct Node {
data: String,
}
#[derive(Debug)]
struct Circuit {
nodes: Vec<Rc<RefCell<Node>>>,
connections: Vec<Connection>,
}
#[derive(Debug)]
struct Connection {
from: Rc<RefCell<Node>>,
to: Rc<RefCell<Node>>,
}

最新更新