Created
May 26, 2023 09:27
-
-
Save lbfalvy/486f88d1e7b984610cbe80b453f44a78 to your computer and use it in GitHub Desktop.
A cool function I didn't want to delete but which had no use in the project
This file contains hidden or 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::fmt::Display; | |
use std::io::{stdin, stdout, BufRead, Write}; | |
pub fn prompt<T: Display, E: Display>( | |
prompt: &str, | |
default: T, | |
mut try_cast: impl FnMut(String) -> Result<T, E>, | |
) -> T { | |
loop { | |
print!("{prompt} ({default}): "); | |
stdout().lock().flush().unwrap(); | |
let mut input = String::with_capacity(100); | |
stdin().lock().read_line(&mut input).unwrap(); | |
if input.is_empty() { | |
return default; | |
} | |
match try_cast(input) { | |
Ok(t) => return t, | |
Err(e) => println!("Error: {e}"), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment