Skip to content

Instantly share code, notes, and snippets.

@SteveLauC
Last active April 9, 2022 08:12
Show Gist options
  • Save SteveLauC/5d841aa0d8386011111e4f85513c7a1b to your computer and use it in GitHub Desktop.
Save SteveLauC/5d841aa0d8386011111e4f85513c7a1b to your computer and use it in GitHub Desktop.
Read an ascii char from stdin in Rust.
use std::io::{Read, stdin};
/*
return: Some(char) on success, None on EOF or error.
*/
fn read_char() -> Option<char> {
stdin().bytes().next().and_then(|res| res.ok()).map(|c| {
char::from(c)
})
}
// res is of type: Result<u8, std::io::Error>
// use res.ok() to turn it into Option<u8>
// and then map Option<u8> to Option<char>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment