rust - 如何在Rust中从标准中获取多个输入?

标签 rust

我想输入2个用户输入,高度和宽度:

fn main() {
    let mut w = String::new();
    let mut l = String::new();
    println!("Enter the width");
    io::stdin().read_line(&mut w).expect("failed to read input");
    let w: i32 = w.trim().parse().expect("invalid input");

    println!("Enter the length");
    io::stdin().read_line(&mut l).expect("failed to read input");
    let l: i32 = l.trim().parse().expect("invalid input");

    println!("width {:?}", w);
    println!("length{:?}", l);
}
有没有更短的方法来实现这一目标?

最佳答案

处理来自终端的输入并不是一件很有趣的事情,因此,许多试图制作的 crate 更短/更容易/更豪华。
可能的候选人是rprompt:

let reply = rprompt::prompt_reply_stdout("Password: ").unwrap();
println!("Your reply is {}", reply);
这可能只是Thomas' advice将所有这些东西包装到您自己的函数中的捷径。我更喜欢使用 crate ,因为它们允许使用一些精美的小功能,例如使用户在输入错误时能够更正其输入内容。
prompty可能值得一看。

关于rust - 如何在Rust中从标准中获取多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63580989/

相关文章:

enums - 为什么这个 Rust 枚举没有变小?

reference - 在 Rust 中,可变借用和不可变借用到底是什么?

windows - cargo 登记更新总是失败

rust - 为什么参数的大小未知?

multithreading - 为什么在将包含 Arc 的 self 移动到新线程时出现 "Sync is not satisfied"错误?

rust - Rust 中未解析的枚举器名称

Rust:从 Slice 的基准内置排序与编译排序代码相比有 x16 差异?

rust - 如何为 Cargo.toml 中的 [build-dependencies] 生成 rustdoc 文档?

asynchronous - 如何限制 async_trait 函数的返回值来实现同步?

regex - 从字符串中删除所有空格