Created
December 5, 2019 20:08
-
-
Save rust-play/e5176e3e14ae0b2c85651ad24108a50e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::iter::Peekable; | |
use std::str::Chars; | |
pub enum Token { | |
E, | |
Rest, | |
} | |
pub struct Lexer<'a> { | |
chars: Peekable<Chars<'a>>, | |
} | |
impl Lexer<'_> { | |
pub fn new(input: &str) -> Lexer { | |
Lexer { | |
chars: input.chars().peekable(), | |
} | |
} | |
fn foo(&mut self) {} | |
// compiles | |
pub fn next(&mut self) -> Option<Token> { | |
match self.chars.peek() { | |
Some(&'e') => { | |
self.foo(); | |
Some(Token::E) | |
} | |
Some(_) => Some(Token::Rest), | |
_ => None, | |
} | |
} | |
// compiler error | |
pub fn next2(&mut self) -> Option<Token> { | |
self.chars.peek().cloned().map(|ch| match ch { | |
'e' => { | |
self.foo(); | |
Token::E | |
} | |
_ => Token::Rest, | |
}) | |
} | |
} | |
fn main() { | |
let input = "Hello"; | |
let mut l = Lexer::new(input); | |
l.next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment