Kevin Burke Kevin Burke - 8 months ago 40
SQL Question

How do I convert a database row into a struct, in Go?

Let's say I have a struct:

type User struct {
Name string
Id int
Score int

And a database table with the same schema. What's the easiest way to parse a database row into a struct? I've added an answer below but I'm not sure it's the best one.


Here's one way to do it - just assign all of the struct values manually in the Scan function.

func getUser(name string) (*User, error) {
    var u User
    // this calls sql.Open, etc.
    db := getConnection()
    // note the below syntax only works for postgres
    err := db.QueryRow("SELECT * FROM users WHERE name = $1", name).Scan(&u.Id, &u.Name, &u.Score)
    if err != nil {
        return &User{}, err
    } else {
        return &u, nil