dsg41888 2018-08-24 15:28
浏览 15
已采纳

使用缓冲区的csv编写器导致空输出

I have created a function to get some data and write them to CSV and the output is stored on a buffer.

type OptIn struct {
    Email      string `json:"email"`
    LastUpdate string `json:"opt_in_last_update"`
}

func writeCSV(data []OptIn) ([]byte, error) {
    var buf bytes.Buffer
    writer := csv.NewWriter(&buf)

    defer writer.Flush()

    for _, obj := range data {
        var record []string
        record = append(record, obj.Email)
        record = append(record, obj.LastUpdate)
        err := writer.Write(record)
        if err != nil {
            panic(err.Error())
        }
    }

    return buf.Bytes(), nil
}

The problem is that the buf.Bytes() is always empty, even though the input is not empty and there are no errors thrown.

  • 写回答

1条回答 默认 最新

  • duandong7980 2018-08-24 15:34
    关注

    You need to call writer.Flush() before calling .Bytes() and check .Error() before returning:

      // TODO: remove `defer writer.Flush()`
      // ...
    
      writer.Flush()
    
      if err := writer.Error(); err != nil {
        return nil, err
      }
    
      return buf.Bytes(), nil
    }
    

    Your sample code does things in the following order:

    1. call buf.Bytes()
    2. return the generated byte slice and nil
    3. call writer.Flush()

    Clearly this is not the intended order since we need to flush (and check for any writer errors!) before accessing the generated byte slice.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分