Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created December 5, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/e5176e3e14ae0b2c85651ad24108a50e to your computer and use it in GitHub Desktop.
Save rust-play/e5176e3e14ae0b2c85651ad24108a50e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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