dre93205 2017-10-11 09:48
浏览 88
已采纳

如何检查golang中tabwriter.Writer返回的响应

I am writting something to tabwriter.Writer object,

    w := tabwriter.NewWriter(os.Stdout, 5, 1, 3, ' ', 0)
    fmt.Fprintf(w, "%v\t%v\t
", somevalue1, somevalue2)

I can print the data in w in console using w.Flush() Is there any way so get values in w as string in one place and compare it with some value?

I want to compare what I have in w with some data.

  • 写回答

1条回答 默认 最新

  • doudong3570 2017-10-11 10:26
    关注

    You can implement your own io.Writer:

    type W []byte
    
    func (w *W) Write(b []byte) (int, error) {
        *w = append(*w, b...)
        return len(b), nil
    }
    

    You can then pass an instance of *W to tabwriter.NewWriter:

    sw := &W{}
    w := tabwriter.NewWriter(sw, 5, 1, 3, ' ', 0)
    fmt.Fprintf(w, "%v\t%v\t
    ", somevalue1, somevalue2)
    
    // get the string value from sw
    str := string(*sw)
    

    As sugested by @Tim, you should use *bytes.Buffer instead for better performance and it already implements io.Writer:

    var b bytes.Buffer
    w := tabwriter.NewWriter(&b, 0, 0, 1, '.', 0)
    // ...
    fmt.Println(b.String())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低