rust - 在 Rust 中实现读取行或睡眠定时器有哪些好方法
问题描述
我已经完成了我的 CLI,但它退出得太快,人们无法使用它,任何人都知道我将如何在我的 main.rs 中实现代码而不破坏编译器哈哈。我在想也许是一个 for 循环,它打印、读取和执行,然后重新开始。或者可能是一个读取行功能,因此它可以保持足够长的时间来输出显示。
你们会在哪里实施呢?谢谢!
use structopt::StructOpt;
mod cli;
mod task;
use cli::{Action::*, CommandLineArgs};
use task::Task;
fn main() {
// Get the command-line arguments.
let CommandLineArgs {
action,
todo_file,
} = CommandLineArgs::from_args();
// Unpack the todo file.
let todo_file = todo_file.expect("Failed to find todo file");
// Perform the action.
match action {
Add { text } => task::add_task(todo_file,
Task::new(text)),
List => task::list_tasks(todo_file),
Done { position } =>
task::complete_task(todo_file, position),
}
.expect("Failed to perform action")
}
解决方案
从示例中,您似乎正在从命令行获取参数。如果您希望程序等待用户输入一些文本,将该文本解释为命令并运行它,然后再次等待输入,直到用户退出程序,那么您可能需要https:// doc.rust-lang.org/std/io/struct.Stdin.html或可能更高级别的箱子,例如https://docs.rs/rustyline/8.0.0/rustyline/
如果您直接使用标准输入,您可以调用io::stdin().read_line()
which 将等到用户输入一行文本并按下回车,然后函数才会返回。然后,您可以解析该字符串以获取要执行的操作。输入/解析/动作代码可以包含在 a 中loop {}
,其中一个动作可以是退出循环的退出命令。
推荐阅读
- javascript - 如何为 JavaScript 代码创建的每个 div 设置样式
- excel-formula - 未找到条目时 Excel 中的筛选功能
- swagger - OpenAPI 3 中的参数重用
- java - ArangoDB、Java 和模块
- amazon-web-services - 使用 terraform 上传 ssl 证书
- sql - 如何在函数中切换源?
- javascript - 401 - 未经 Azure AD 授权,使用 passport-azure-ad-oauth2
- python - Python版本+要求
- html - 我可以使用 CSS 动态更改通过标签呈现的 svg 的颜色吗?
- blazor - 参数/CascadingParameter 不更新对象