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?
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:
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.