Unmarshal CSV Records into Go Structs
Question:
How can I automatically unmarshal records from a CSV file into Go structs?
For instance, consider the following Go struct:
type Test struct { Name string Surname string Age int }
And a CSV file containing records:
John;Smith;42 Piter;Abel;50
Is there an efficient way to unmarshal these records into structs without manually parsing each record and assigning values?
Answer:
Yes, utilizing gocarina/gocsv is an effective method. It allows for the creation of unmarshalling and marshalling functions for custom types, similar to the functionality provided by encoding/json.
Example:
type Client struct { Id string `csv:"client_id"` // .csv column headers 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) } }
By employing gocsv, custom unmarshaller and marshaller functions are defined for the Client type. These functions effectively translate between the CSV format and Go structs, making the unmarshaling process straightforward and efficient.
The above is the detailed content of How to Efficiently Unmarshal CSV Data into Go Structs?. For more information, please follow other related articles on the PHP Chinese website!