input_rust/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::fmt::Display;
use std::io::{self, Write};

pub fn input(msg: impl Display) -> io::Result<String> {
    print!("{}", msg.to_string());
    io::stdout().flush()?;

    let mut text = String::new();
    match io::stdin().read_line(&mut text) {
        Ok(_) => {
            let trimmed = text.trim();
            if trimmed.is_empty() {
                Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Input cannot be empty",
                ))
            } else {
                Ok(trimmed.to_string())
            }
        }
        Err(e) => {
            Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
        }
    }
}