How to have an in-place string that updates on stdout

user1529891 picture user1529891 · Mar 15, 2013 · Viewed 26k times · Source

I want to output to stdout and have the output "overwrite" the previous output.

For example; if I output On 1/10, I want the next output On 2/10 to overwrite On 1/10. How can I do this?

Answer

zzzz picture zzzz · Mar 15, 2013

stdout is a stream (io.Writer). You cannot modify what was already written to it. What can be changed is how that stream's represented in case it is printed to a terminal. Note that there's no good reason to assume this scenario. For example, a user could redirect stdout to a pipe or to a file at will.

So the proper approach is to first check:

  • if the stdout is going to a terminal
  • what is that terminal's procedure to overwrite a line/screen

Both of the above are out of this question's scope, but let's assume that a terminal is our device. Then usually, printing:

fmt.Printf("\rOn %d/10", i)

will overwrite the previous line in the terminal. \r stands for carriage return, implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the "overwrite line" facility.

As an example of "other" terminal with a differently supported 'overwriting', here is an example at the playground.