I'm trying to make a status indicator in Rust that prints to stdout. In other languages, I've used a function that clears the current line of stdout while leaving the others untouched. I can't seem to find a Rust equivalent. Is there one? Here's a small example of what I'm looking for
for i in 0..1000 {
stdio::print(format!("{}", i).as_slice));
stdio::clear();
}
On an ANSI terminal (almost everything except Command Prompt on Windows), \r
will return the cursor to the start of the current line, allowing you to write something else on top of it (new content or whitespace to erase what you have already written).
print!("\r")
There is nothing available in the standard library to do this in a platform-neutral manner.
cli is a crate (docs) which seems to work very well for solving this very problem. It also comes with some other common goodies like progress bars and styled prompts.
cli::clear
should be the function you want.
The main difficulty with using something like repeated:
println!("\r");
is that this will not be cross OS compatible while using cli::clear should be as long as the OS in question is supported. The other nice thing about using the cli crate here is that it's a higher level of abstraction which conveys your actual meaning in a clear way.
You want to clear the terminal.
You aren't trying to repeatedly get a carriage return.
There are other routines in here for similar things. Namely the progress bar which is the problem you are trying to solve.
Utilizing the ASCII code for backspace is one option, for example:
print!("12345");
print!("{}", (8u8 as char));
This will end up outputting "1234" after the 5 is removed as a result of printing the backspace character (ascii code 8). Strangely, Rust does not recognize \b as a valid character escape.