In Go, there's a common need to deserialize CSV records into custom structures. While the "encoding/csv" package provides basic CSV reading, it requires manual parsing and conversion into structs. Fortunately, there are alternative solutions that simplify this process.
One such solution is gocarina/gocsv, which follows the same approach as the "encoding/json" package for handling custom structs. It also allows for custom marshalling and unmarshalling for specific types.
Consider the example:
type Client struct { Id string `csv:"client_id"` Name string `csv:"client_name"` Age string `csv:"client_age"` } func main() { in, err := os.Open("clients.csv") if err != nil { panic(err) } defer in.Close() clients := []*Client{} if err := gocsv.UnmarshalFile(in, &clients); err != nil { panic(err) } for _, client := range clients { fmt.Println("Hello, ", client.Name) } }
Here, gocsv.UnmarshalFile directly populates the clients slice with deserialized Client structs. This simplifies the unmarshalling process, making it more intuitive and convenient than using standard "encoding/csv" methods.
The above is the detailed content of How Can I Efficiently Unmarshal CSV Data into Go Structs?. For more information, please follow other related articles on the PHP Chinese website!