Home > Backend Development > Golang > How Can I Efficiently Unmarshal CSV Data into Go Structs?

How Can I Efficiently Unmarshal CSV Data into Go Structs?

Barbara Streisand
Release: 2024-12-11 15:32:17
Original
182 people have browsed it

How Can I Efficiently Unmarshal CSV Data into Go Structs?

Unmarshal CSV Records into Go Structs

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template