How to block console from exiting?

Hi guys ! i am new in rust-lang, and i dont know how can i stop console from exiting immediately…
In c++ i used std::cin.get(), std::getchar(), in C# Console.ReadLine();.
What should i use in rust-lang?

The closest equivalent in Rust is probably (mis)using Stdin::read_line:

use std::io;

fn main() {
    println!("Going to wait...");
    io::stdin().read_line(&mut String::new()).unwrap();
}

To explain a couple of the weird bits:

  • You have to provide a mutable reference to a String buffer to read the line into - usually you’d define a separate variable for this, but since we don’t care about the actual input, we can just create one and immediately throw it away.
  • read_line returns a Result which will either tell you how many bytes were read or give you an error message if stdin couldn’t be accessed. Again, if we cared about this, we could handle it properly, but we don’t, so we just unwrap it. You could leave the unwrap off, but then you’d get a compiler warning for not handling the Result.

If you want to see how you’d use read_line properly, have a look at the example in the docs, but if all you care about is having a simple bit of code to stop the console from closing, this will work :slight_smile:

4 Likes

The one and only and correct way is to fire up the console, cd to your project, build it and run it. Terminal will stay open this way and you can rebuild the application as often as you want.

2 Likes

Thank you very much! :slight_smile:

Crossterm supports this behavior pl ase checkout this example.