Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. fn main() {
  4. // I want to check of the the last element of v is an opening bracket that
  5. // can be closed by maybe_closing_char
  6. let v = ['a', 'b', 'c', '('];
  7. let maybe_closing_char = ')';
  8. // closing_char should tell me which charater would be fitting to close the
  9. // brackets. We need an Option for that, because we can't be sure there is
  10. // any such character.
  11. // This works
  12. let closing_char = match v.last() {
  13. Some('[') => Some(']'),
  14. Some('(') => Some(')'),
  15. Some('{') => Some('}'),
  16. _ => None,
  17. };
  18. // I would like to use a HashMap instead (so I can reuse it later).
  19. // This seems to be more elegant, but doesn't work. The &* were inserted in
  20. // an attempt to satisfy the compilier.
  21. let brackets_matchers: HashMap<char, char> =
  22. [('(', ')'),
  23. ('[', ']'),
  24. ('{', '}')]
  25. .iter().cloned().collect(); // easiest way to create a HashMap I know of
  26. // comment out this line to see it working
  27. let closing_char = v.last().and_then(|l| brackets_matchers.get(&*l));
  28.  
  29. if Some(maybe_closing_char) == closing_char {
  30. println!("Can close")
  31. } else {
  32. println!("Can't close")
  33. }
  34.  
  35. println!("closing_char: {:?}", closing_char);
  36. println!("Hello, world!");
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement