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.

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

报告相同问题?