Last active
April 9, 2022 08:12
-
-
Save SteveLauC/5d841aa0d8386011111e4f85513c7a1b to your computer and use it in GitHub Desktop.
Read an ascii char from stdin in Rust.
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::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