duanhuang1967 2019-06-25 09:37
浏览 130
已采纳

编写完字符串后,golang io.writer新行

I have the following code that uses a package to draw a progress bar

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)
        }
    }
}

All works, except there is no new line at the end as you can see here enter image description here

I can't add a new line character in the Write function as that will cause it to new line after every byte pushed to the writer. Is there a neat way can I do this?

EDIT: I want the new line after the progress bar and before the next line prints out

  • 写回答

1条回答 默认 最新

  • doutao8774 2019-06-25 10:26
    关注

    The simple answer to the question you've asked is simply to print an additional newline after the progress bar is complete:

    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, "
    ") // <---- Add this
    }
    

    Although your comments indicate that this is problematic, but you haven't explained how. If you update your question to explain why this is a problem, perhaps a better solution can follow.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?