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/some_tester.rs (line 23)
22fn test_io() {
23    let age = read_input::<u32>(Some("Enter your age: ")).unwrap();
24    let name = read_input::<String>(Some("Enter your name: ")).unwrap();
25    println!("Hello, {}! You are {} years old.", name, age);
26}
27
28fn test_pause() {
29    read_input::<i128>(Some("Press Enter to continue...")); // * Input prompt
30    read_input::<String>(None); // * Silent pause
31}