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

How to Efficiently Unmarshal CSV Data into Go Structs?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 17:18:10830browse

How to Efficiently Unmarshal CSV Data into Go Structs?

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!

Statement:
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