添加对参考列表的引用

时间:2017-12-03 04:31:57

标签: reference rust

我正在实施基本数据结构。我想我理解为什么下面的代码不起作用:我不能同时借用并尝试访问(读取)该值。但是,我仍然坚持如何实施add_ege

整个想法是让Graph在堆中保存Node列表。 Node本身跟踪相邻节点(边缘)。我不希望Node保留Node的副本,我希望它能够引用Node中保存的任何Graph

struct Node<'a> {
    value: String,
    adj_nodes: Vec<&'a Node<'a>>, // refer to Graph.nodes
}

pub struct Graph<'a> {
    nodes: Vec<Box<Node<'a>>>,
}

fn mk_node<'a>(value: String) -> Node<'a> {
    Node {
        value,
        adj_nodes: vec![],
    }
}

pub fn mk_graph<'a>() -> Graph<'a> {
    let nodes = vec![];
    Graph { nodes }
}

impl<'a> Graph<'a> {
    fn add_node(&mut self, val: String) {
        let node = Box::new(mk_node(val));
        self.nodes.push(node);
    }

    fn add_edge(&mut self, from_node: &'a mut Node<'a>, to_node: &'a mut Node<'a>) {
        from_node.adj_nodes.push(to_node);
        // won't work because I already have from_node as mutable borrow
        to_node.adj_nodes.push(from_node);
    }
}

有办法做到这一点吗?

0 个答案:

没有答案