Guest User

Untitled

a guest
Sep 25th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #![feature(nll)]
  2.  
  3. use std::collections::HashMap;
  4.  
  5. struct Node {
  6. children: HashMap<String, Option<Box<Node>>>,
  7. }
  8.  
  9. fn main() {
  10. let mut node = Node::new("xyz");
  11.  
  12. // cur_node was in another function and pointed to root of tree.
  13. let mut cur_node = &mut node;
  14.  
  15. // I wanted to traverse the nodes.
  16. // So, The if block in this gets a immutable reference to node
  17. // The code in else tries to get a mutable reference and update the node.
  18. // but it doesn't works! because cur_node.children.get() has a mutable reference and there can only be one mutable reference.
  19. if let Some(node) = cur_node.children.get_mut("abc") {
  20. cur_node = node.as_mut().unwrap();
  21. } else {
  22. // Create folder
  23. let n = Box::new(Node::new("abc"));
  24.  
  25. // This does not works. It returns as_mut not found on &Node
  26. cur_node.children.insert("abc".into(), Some(n));
  27. }
  28. }
  29.  
  30. impl Node {
  31. fn new(name: &str) -> Node {
  32. let mut h = HashMap::new();
  33. h.insert(name.to_owned(), None);
  34. Node { children: h }
  35. }
  36. }
Add Comment
Please, Sign In to add comment