1 回答

TA貢獻1824條經驗 獲得超6個贊
一般來說,您不能簡單地從一種類型映射到另一種類型并讓編譯器弄清楚如何轉換數據。其他語言可能會提供一些語法糖或有一些推斷合理默認值的先例,但 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 關注
- 186 瀏覽
添加回答
舉報