1 回答
TA贡献2051条经验 获得超10个赞
通常,您不能简单地从一种类型映射到另一种类型并让编译器弄清楚如何转换您的数据。其他语言可能会提供一些语法糖或有一些推断合理默认值的先例,但 Go 故意不提供这种魔法。
您需要明确指出如何将数据结构的每个实例转换为要写为 CSV 行models.EndModel的切片。[]string
类似于以下内容:
// writeCSV is a function create a .csv file
func writeCSV(allData []models.EndModel) {
today := time.Now().Format("2006-01-02")
fileString := fmt.Sprintf("result-%v.csv", today)
//Create File
file, err := os.Create(fileString)
checkError("Cannot create file", err)
defer file.Close()
// Create the writer with the file
writer := csv.NewWriter(file)
defer writer.Flush()
// Create and Write to the CSV
csvRows := make([][]string, len(allData))
for i, model := range allData {
csvRows[i] = []string{
// Choose the ordering you wish in your output CSV
model.IncidentNumber,
model.Title,
model.CreatedAt,
model.Notes,
}
}
// Note that you need to call WriteAll to pass multiple rows
err = writer.WriteAll(csvRows)
checkError("Cannot write to file...", err)
}
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报