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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 求一款能支持ios15以上的屏蔽越狱插件。比较好用的
  • ¥15 C++ QT对比内存字符(形式不定)
  • ¥30 C++第三方库libiconv 远程安装协助
  • ¥15 https://github.com/youlaitech/vue3-element-admin/blob/master/src/store/modules/user.ts 这2句代码如何理解
  • ¥15 duilib开发文本字串超过长度显示
  • ¥20 mysql的.ibd文件为啥那么多
  • ¥15 C++中采用栈和BFS算法求解迷宫问题
  • ¥15 关于#java#的问题:这是跳转失败出现的界面这是哪个出现问题的servlet(开发工具-ide)
  • ¥15 EBS R12费用采购跨月冲销
  • ¥15 python中用mplfinance如何做到多股同列?