Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- fn main() {
- // I want to check of the the last element of v is an opening bracket that
- // can be closed by maybe_closing_char
- let v = ['a', 'b', 'c', '('];
- let maybe_closing_char = ')';
- // closing_char should tell me which charater would be fitting to close the
- // brackets. We need an Option for that, because we can't be sure there is
- // any such character.
- // This works
- let closing_char = match v.last() {
- Some('[') => Some(']'),
- Some('(') => Some(')'),
- Some('{') => Some('}'),
- _ => None,
- };
- // I would like to use a HashMap instead (so I can reuse it later).
- // This seems to be more elegant, but doesn't work. The &* were inserted in
- // an attempt to satisfy the compilier.
- let brackets_matchers: HashMap<char, char> =
- [('(', ')'),
- ('[', ']'),
- ('{', '}')]
- .iter().cloned().collect(); // easiest way to create a HashMap I know of
- // comment out this line to see it working
- let closing_char = v.last().and_then(|l| brackets_matchers.get(&*l));
- if Some(maybe_closing_char) == closing_char {
- println!("Can close")
- } else {
- println!("Can't close")
- }
- println!("closing_char: {:?}", closing_char);
- println!("Hello, world!");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement