golang io.writer 写完字符串后换行

golang io.writer new line after finished writing string

我有以下使用 a package 绘制进度条的代码

type tmpStruct struct {
}

func (t *tmpStruct) Write(p []byte) (n int, err error) {
    fmt.Fprintf(os.Stdout, "%s", string(p))
    return len(p), nil
}

func demoLoadingBarCount(maximumInt int) {
    buf := tmpStruct{}
    if nBuf, ok := interface{}(&buf).(io.Writer); ok {
        bar := progressbar.NewOptions(
            maximumInt,
            progressbar.OptionSetTheme(progressbar.Theme{Saucer: "█", SaucerPadding: "-", BarStart: ">", BarEnd: "<"}),
            progressbar.OptionSetWidth(100),
            progressbar.OptionSetWriter(nBuf),
        )
        for i := 0; i < maximumInt; i++ {
            bar.Add(1)
            time.Sleep(10 * time.Millisecond)
        }
    }
}

一切正常,除了最后没有换行,如您在此处看到的

我无法在 Write 函数中添加换行符,因为这会导致在将每个字节推送到编写器后换行。有什么好的方法可以做到这一点吗?

编辑: 我想要新行在进度条之后和下一行打印出来之前

您所提问题的简单答案是在进度条完成后打印一个额外的换行符:

func demoLoadingBarCount(maximumInt int) {
    buf := &tmpStruct{}
    bar := progressbar.NewOptions(
        maximumInt,
        progressbar.OptionSetTheme(progressbar.Theme{Saucer: "█", SaucerPadding: "-", BarStart: ">", BarEnd: "<"}),
        progressbar.OptionSetWidth(100),
        progressbar.OptionSetWriter(buf),
    )
    for i := 0; i < maximumInt; i++ {
        bar.Add(1)
        time.Sleep(10 * time.Millisecond)
    }
    fmt.Fprintf(buf, "\n") // <---- Add this
}

虽然你的评论表明这是有问题的,但你没有解释如何。如果你更新你的问题来解释为什么这是一个问题,也许可以找到更好的解决方案。