我正在学习Rust,但我不太明白为什么它不起作用。#[derive(Debug)]struct Node { value: String,}#[derive(Debug)]pub struct Graph { nodes: Vec<Box<Node>>,}fn mk_node(value: String) -> Node { Node { value }}pub fn mk_graph() -> Graph { Graph { nodes: vec![] }}impl Graph { fn add_node(&mut self, value: String) { if let None = self.nodes.iter().position(|node| node.value == value) { let node = Box::new(mk_node(value)); self.nodes.push(node); }; } fn get_node_by_value(&self, value: &str) -> Option<&Node> { match self.nodes.iter().position(|node| node.value == *value) { None => None, Some(idx) => self.nodes.get(idx).map(|n| &**n), } }}#[cfg(test)]mod tests { use super::*; #[test] fn some_test() { let mut graph = mk_graph(); graph.add_node("source".to_string()); graph.add_node("destination".to_string()); let source = graph.get_node_by_value("source").unwrap(); let dest = graph.get_node_by_value("destination").unwrap(); graph.add_node("destination".to_string()); }}这有错误error[E0502]: cannot borrow `graph` as mutable because it is also borrowed as immutable --> src/main.rs:50:9 |47 | let source = graph.get_node_by_value("source").unwrap(); | ----- immutable borrow occurs here...50 | graph.add_node("destination".to_string()); | ^^^^^ mutable borrow occurs here51 | } | - immutable borrow ends here来自Rust编程的示例与我的示例非常相似,但是可以正常工作:pub struct Queue { older: Vec<char>, // older elements, eldest last. younger: Vec<char>, // younger elements, youngest last.}impl Queue { /// Push a character onto the back of a queue. pub fn push(&mut self, c: char) { self.younger.push(c); }
3 回答
温温酱
TA贡献1752条经验 获得超4个赞
在您的示例中,@ Shepmaster而不是last()返回引用...如果移出该值怎么办?那么,在vec内部将没有引用,并且在声明之后,不可变的借位将在此处结束吗?(这只是假设的情况。如果它返回一个拥有的值。.last()将是&而不是&mut)
- 3 回答
- 0 关注
- 413 浏览
添加回答
举报
0/150
提交
取消