1 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
一般來(lái)說(shuō),您不能簡(jiǎn)單地從一種類型映射到另一種類型并讓編譯器弄清楚如何轉(zhuǎn)換數(shù)據(jù)。其他語(yǔ)言可能會(huì)提供一些語(yǔ)法糖或有一些推斷合理默認(rèn)值的先例,但 Go 故意不提供這種魔力。
您需要明確指示如何將數(shù)據(jù)結(jié)構(gòu)的每個(gè)實(shí)例轉(zhuǎn)換為要作為 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 關(guān)注
- 198 瀏覽
添加回答
舉報(bào)