简体   繁体   English

如何使用泛型类型在 Rust 中实现类似 python 的输入 function?

[英]How to implement a python-like input function in Rust using generic types?

I made a python-like input function to get stdin and return a String.我做了一个类似 python 的输入 function 来获取标准输入并返回一个字符串。 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.但是,我决定将解析移至 function 并在其上使用泛型类型,然后出现错误。

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:此外,在 VSCode 中,还会显示此消息:

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.我想我可以使用枚举来解决这个问题,但是很难写下 println 接受的所有可能类型,并且使用条件语句似乎更糟。 I've been studying Rust for three days so far and I don't really know the right approach.到目前为止,我一直在研究 Rust 三天,我真的不知道正确的方法。

The compiler tells you what to do:编译器告诉你该怎么做:

use std::str::FromStr;

fn input<T: FromStr>(text: &str) -> T {
//        ^^^^^^^^^

This bounds the generic type T and says that it must implement the FromStr trait, which is required for .parse::<T>() to work (the parse function bounds on T: FromStr as well).限制了泛型类型T并表示它必须实现FromStr特征,这是.parse::<T>()工作所必需的( parse function 也限制在T: FromStr上)。

Further reading:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM