I made a python-like input function to get stdin and return a String. It was working fine, I got the result and it was parsing into whatever numeric type needed. But, I decided to move parsing to the function and use a generic type on it, then I got an error.
Here's the code:
fn input<T>(text: &str) -> T {
let mut input = String::new();
println!("{}", text);
std::io::stdin()
.read_line(&mut input)
.expect("Erro ao ler valor");
let input = input.trim().parse::<T>().expect("Erro ao ler valor");
return input;
}
The error in compilation:
let input = input.trim().parse::<T>().expect("Erro ao ler valor");
^^^^^ the trait `FromStr` is not implemented for `T`
Also, in VSCode, this message is shown:
main.rs(9, 11): consider restricting type parameter `T`: `: std::str::FromStr`
I think I could use enumeration to fix this, but it would be hard to write down every possible type accepted by println, and use conditional statement seems to be even worse. I've been studying Rust for three days so far and I don't really know the right approach.