#用户输入 #输入 #验证 #命令行输入 #验证

input_validation

接收并验证用户 CLI 输入以匹配程序所需类型

2 个版本

0.1.2 2023年11月13日
0.1.1 2023年3月29日

#640 in 命令行界面

MIT/Apache

14KB
151

License: MIT

输入通用输入验证

提示用户输入并将其解析为请求的类型值。如果提供的是不正确的响应,用户将被提示再次输入,直到他们给出正确的响应。

安装

要在项目中使用此库,请在您的 Cargo.toml 文件中添加 input_validation,或者运行 'cargo add input_validation`。

使用方法

use input_validation::{get_input,get_bool,get_list,get_choice, get_email};

fn main() {
    let name: String = get_input("What is your name? ");
    println!("Hello, {}", name);

    let age: u8 = get_input("What is your age? ");
    println!("Your are {} years old.", age);

    let is_cool: bool = get_bool("Are you cool? ");
    println!("You are{} cool!", if is_cool { ""} else {" not"});

    let choices = &["Apples", "Oranges", "Bananas"];
    let favorite_fruit = get_choice("What is your favorite fruit? ",choices);
    println!("Your favorite fruit is: {}", choices[favorite_fruit]);

    let names: Vec<String> = get_list("Enter some names, separated by commas: ", ",");
    println!("You entered: {:?}", names);

    let numbers: Vec<i64> = get_list("Enter some numbers, separated by commas: ", ",");
    println!("You entered: {:?}", numbers);

    let email = get_email("Enter your email address: ");
    println!("Your email address is: {}", email);
}

示例输出

What is your name? 4
Hello, 4
What is your age? John Smith
What is your age? 43
Your are 43 years old.
Are you cool? k
Are you cool? Y
You are cool!
What is your favorite fruit?  (Apples/Oranges/Bananas) apple
What is your favorite fruit?  (Apples/Oranges/Bananas) apples
Your favorite fruit is: Apples
Enter some names, separated by commas: John Cougar, Fred Flintstone, Mary Cooper, violet beauregarde 
You entered: ["John Cougar", "Fred Flintstone", "Mary Cooper", "violet beauregarde"]
Enter some numbers, separated by commas: j, k, w, 3
Enter some numbers, separated by commas: 1, 5, 3, 98, 42
You entered: [1, 5, 3, 98, 42]
Enter your email address: john@example.com
Your email address is: john@example.com

贡献

欢迎提交拉取请求。对于重大更改,请首先打开一个问题来讨论您想进行更改的内容。

许可

MIT

依赖

~2.2–3MB
~54K SLoC