亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不能借來可變,因為它也借來不可變

不能借來可變,因為它也借來不可變

Git
拉莫斯之舞 2019-11-04 09:18:39
我正在學習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)

查看完整回答
反對 回復 2019-11-04
  • 3 回答
  • 0 關注
  • 447 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號