我有一个结构作为值的地图,如下所示:
type Record struct { ID int 输入字符串 年份字符串}
m:= make(map [int]记录)一旦我用一些记录填充这张地图,我就是……
您的代码有几个问题。尝试这样的事情:
package main import ( "encoding/csv" "os" "strconv" ) func main() { type Record struct { ID int Type string Year string } m := make(map[int]Record) r := Record{ID: 1, Type: "A", Year: "2019"} m[r.ID] = r f, err := os.Create("export.csv") if err != nil { // handle error } defer f.Close() w := csv.NewWriter(f) defer w.Flush() for _, v := range m { r := make([]string, 0, 3) r = append(r, strconv.Itoa(v.ID)) r = append(r, v.Type) r = append(r, v.Year) err := w.Write(r) if err != nil { // handle error } } }
输出:
$ go run export.go $ cat export.csv 1,A,2019 $
你正在尝试申请 len() 在结构而不是地图上 请尝试以下方法:
len()
file, err := os.Create("export.csv") checkError("Error:", err) defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() r := make([]string, 0, 1+len(m)) for key, value := range m { r = append(r, key) r = append(r, value) } writer.Flush()
这里有一些问题:
writer.Write
[]string
r
len
我对你的代码做了一些修改:
len(headers)
测试 这里 在Go Playground。
例:
type Record struct { ID int Type string Year string } m := make(map[int]Record) // populate this map with some records file, err := os.Create("export.csv") checkError("Error:", err) defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() // define column headers headers := []string{ "id", "type", "year", } // write column headers writer.Write(headers) var idString string for key := range m { r := make([]string, 0, 1+len(headers)) // capacity of 4, 1 + the number of properties your struct has & the number of column headers you are passing // convert the Record.ID to a string in order to pass into []string idString = strconv.Itoa(m[key].ID) r = append( r, idString, m[key].Type, m[key].Year, ) writer.Write(r) }