Skip to content

Instantly share code, notes, and snippets.

@sheepla
Created March 18, 2025 12:07
Show Gist options
  • Save sheepla/1ef7c10ee9012bde0d59d60e949f72ad to your computer and use it in GitHub Desktop.
Save sheepla/1ef7c10ee9012bde0d59d60e949f72ad to your computer and use it in GitHub Desktop.
Confim prompt in Rust
mod cli {
use std::io::Write;
#[derive(Debug, thiserror::Error)]
pub enum CliError {
#[error("failed to flush stdout: {0}")]
Flush(std::io::Error),
#[error("failed read line: {0}")]
ReadLine(std::io::Error),
}
pub fn confirm(prompt: &str) -> Result<bool, CliError> {
loop {
print!("{} (Y/n): ", prompt);
std::io::stdout().flush().map_err(CliError::Flush)?;
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.map_err(CliError::ReadLine)?;
match input.trim().to_lowercase().as_str() {
"y" | "yes" => return Ok(true),
"" => {
println!("Yes");
std::io::stdout().flush().map_err(CliError::Flush)?;
return Ok(true);
}
"n" | "no" => return Ok(false),
_ => {
println!("Invalid input. Please enter 'y' or 'n'.")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment