Skip to content

Instantly share code, notes, and snippets.

@lbfalvy
Created May 26, 2023 09:27
Show Gist options
  • Save lbfalvy/486f88d1e7b984610cbe80b453f44a78 to your computer and use it in GitHub Desktop.
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
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