How to clear current stdout line?

I am trying to make a status indicator in Rust that prints to stdout. In other languages, I used a function that clears the current stdout line, leaving the rest untouched. I can not find the equivalent of rust. Is there any? Here is a small example of what I'm looking for

for i in 0..1000 { stdio::print(format!("{}", i).as_slice)); stdio::clear(); } 
+5
source share
3 answers

On the ANSI terminal (almost everything except the command line on Windows), \r will return the cursor to the beginning of the current line, allowing you to write something else on top of it (new content or a space to erase what you already wrote).

 print!("\r") 

There is nothing in the standard library available in a neutral platform.

+5
source

cli is a box ( docs ) which seems to work very well to solve this very problem. It also comes with some other common goodies, such as progress bars and style invitations.

cli::clear should be the function you want.

The main difficulty with using something like repetition:

 println!("\r"); 

is that it will not be compatible with the OS, but when using cli :: clear should be as long as the OS is supported. Another nice thing about using cli is that it is a higher level of abstraction that clearly conveys your actual meaning.

You want to clear the terminal.

You are not trying to re-receive a carriage return.

There are other routines for such things. Namely, a progress bar, which is the problem you are trying to solve.

+2
source

Using ASCII code for backspace is one of the options, for example:

 print!("12345"); print!("{}", (8u8 as char)); 

This will lead to the output of "1234" after removing 5 by printing the backspace character (ascii code 8). Oddly enough, Rust does not recognize \ b as a valid escape character.

0
source

Source: https://habr.com/ru/post/1214525/


All Articles