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 aResult
which will either tell you how many bytes were read or give you an error message ifstdin
couldn't be accessed. Again, if we cared about this, we could handle it properly, but we don't, so we justunwrap
it. You could leave the unwrap off, but then you'd get a compiler warning for not handling theResult
.
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
3 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!
Crossterm supports this behavior pl ase checkout this example.