Function read_input

Source
pub fn read_input<T>(prompt: Option<&str>) -> Result<T, String>
where T: FromStr + Default, <T as FromStr>::Err: Display,
Expand description

Reads input from the console, optionally displaying a prompt message.

This function can:

  • Display a custom prompt message
  • Read input until the user presses Enter
  • Parse the input into any type that implements FromStr
  • Act as a pause mechanism when no prompt is provided

§Type Parameters

  • T: The type to parse the input into. Must implement FromStr and Default.

§Arguments

  • prompt: An optional prompt message to display before reading input.

§Returns

  • T: The parsed input value
  • String: The raw input string if parsing fails or no parsing is needed

§Examples

let number: i32 = read_input(Some("Enter a number: ")).unwrap();
let name: String = read_input(Some("Enter your name: ")).unwrap();
read_input::<String>(None); // Acts as a pause
Examples found in repository?
examples/main_tester.rs (line 24)
23fn test_io() {
24    let age = read_input::<u32>(Some("Enter your age: ")).unwrap();
25    let name = read_input::<String>(Some("Enter your name: ")).unwrap();
26    println!("Hello, {}! You are {} years old.", name, age);    
27}
28
29fn test_pause() {
30    read_input::<i128>(Some("Press Enter to continue..."));  // * Input prompt
31    read_input::<String>(None);  // * Silent pause
32}