我正在尝试为我的抽象节点系统写一个渲染器。
每个节点在一个电路上,它看起来像:
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
错误。
我试过使用RefCell
和Mutex
,但没有成功。我找不到能很好地解释这个问题的资源。
也许你想包装你的节点在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>>,
}