How to Scan Query Results into Structs in Go

Use the Scan method with pointers to struct fields to map database query results to Go structs.

Use the Scan or ScanSlice method on your database row to map columns directly to struct fields.

type User struct {
    ID   int
    Name string
}

var u User
err := db.QueryRow("SELECT id, name FROM users WHERE id = ?", 1).Scan(&u.ID, &u.Name)
if err != nil {
    log.Fatal(err)
}

For multiple rows, iterate with Rows.Scan inside a loop.

rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var users []User
for rows.Next() {
    var u User
    if err := rows.Scan(&u.ID, &u.Name); err != nil {
        log.Fatal(err)
    }
    users = append(users, u)
}
if err := rows.Err(); err != nil {
    log.Fatal(err)
}

The database/sql package requires you to pass pointers to the struct fields in the exact order of the selected columns.