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

前端 未结 4 783
粉色の甜心
粉色の甜心 2021-01-30 03:57

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

4条回答
  •  萌比男神i
    2021-01-30 04:41

    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.

提交回复
热议问题