Rust's equivalent of C's system('pause')


#1

So admittedly i’m spoiled by Visual Studio and the Rust plugin for it is fantastic but I would like to ‘elegantly’ make the program pause at the end before closing, similar to C/C++'s “Press any key to continue” which is provided by System(‘pause’).

I know I could just ask for additional input at the end, but that seems a little clunky to me. Is there such a thing in Rust lang at the moment?


#2

The literal equivalent would probably be:

use std::process::Command;

let _ = Command::new("pause").status();

This constructs a new Command object to execute an external command, and executes it, discarding the result since we don’t really care what it returned. I say “probably” because I’m not on Windows and can’t test it; it’s possible that this won’t work if pause is a shell builtin rather than an external command.

Of course, this isn’t portable, but I don’t know if there is any portable way to get a single character of input for a “Press any key to continue” prompt.


#3

Pause is a command on Windows, but it should work with :
let _ = Command::new("cmd.exe").arg("/c").arg("pause").status()


#4

Calling an OS-specific shell command to prompt for input for you is more clunky than just doing it yourself, IMO.

use std::io;
use std::io::prelude::*;

fn pause() {
    let mut stdin = io::stdin();
    let mut stdout = io::stdout();

    // We want the cursor to stay at the end of the line, so we print without a newline and flush manually.
    write!(stdout, "Press any key to continue...").unwrap();
    stdout.flush().unwrap();

    // Read a single byte and discard
    let _ = stdin.read(&mut [0u8]).unwrap();
}

fn main() {
    // Do some stuff
    pause();
}

#5

The problem is that without platform-specific methods to enable raw input, you’ll only see input once “enter” has been pressed. So “Press any key to continue…” isn’t accurate here. You could do this and say “Press enter to continue…” or “Press return to continue…”, but you need something platform specific if you want any key to be able to dismiss it.