简体   繁体   中英

Rust: access mutable argument in “while let”

But for example in the following code, I want to insert a value into a mutable BTreeMap/Hashmap in each loop, my simple solution triggered an error, what is the elegant way to do that in Rust?

Do I need clone the BTreeMap at the beginning of each loop?

pub fn build_string(word: &str, trie: &mut BTreeMap<&str, &Node>, word_index: usize) {
    for char in  word.chars() {
        let char_label = char.to_string();
        let insert_node = Node::new(&char_label, word_index);
        let insert_result = trie.insert(&char_label, &insert_node);
        println!("char: {}, at index", char);
    }
}

error is

error[E0597]: `insert_node` does not live long enough
  --> src/lib.rs:69:54
   |
65 | pub fn build_string(word: &str, trie: &mut BTreeMap<&str, &Node>, word_index: usize) {
   |                                                           - let's call the lifetime of this reference `'1`
...
69 |         let insert_result = trie.insert(&char_label, &insert_node);
   |                             -------------------------^^^^^^^^^^^^-
   |                             |                        |
   |                             |                        borrowed value does not live long enough
   |                             argument requires that `insert_node` is borrowed for `'1`
70 |         println!("char: {}, at index", char);
71 |     }
   |     - `insert_node` dropped here while still borrowed

The issue is not with your BTreeMap but rather with the lifetime of your Node . You are creating a node inside the method build_string and trying to insert a reference to it into the map. However, once the method build_string goes out of scope, the local insert_node gets dropped but the reference would still exist in the tree. This is not allowed.

Therefore, you could change the BTreeMap to have values of Node instead of &Node . Then you would simply insert the insert_node into the tree which would take ownership of the node thus avoiding any reference leaks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM