首页 > 解决方案 > 在 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")

  }

标签: rustcommand-line-interfacerust-cargo

解决方案


从示例中,您似乎正在从命令行获取参数。如果您希望程序等待用户输入一些文本,将该文本解释为命令并运行它,然后再次等待输入,直到用户退出程序,那么您可能需要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 {},其中一个动作可以是退出循环的退出命令。


推荐阅读