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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?