How do I map rows to structs using pgx?

In Go, using the pgx library to map rows from a database query to structs is quite straightforward. The pgx package provides an efficient way to interact with PostgreSQL databases, allowing you to scan rows directly into your Go structs.

Mapping Rows to Structs Using pgx

To map rows to structs, you’ll first define your struct that matches the columns of the database table. Then, you can use the pgx package to execute your query and scan the results into your struct.

Example

package main import ( "context" "database/sql" "fmt" "log" "github.com/jackc/pgx/v4/pgxpool" _ "github.com/lib/pq" ) type User struct { ID int64 Name string Email string } func main() { db, err := pgxpool.Connect(context.Background(), "postgres://user:password@localhost:5432/mydb") if err != nil { log.Fatal(err) } defer db.Close() var users []User rows, err := db.Query(context.Background(), "SELECT id, name, email FROM users") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var user User err = rows.Scan(&user.ID, &user.Name, &user.Email) if err != nil { log.Fatal(err) } users = append(users, user) } if err = rows.Err(); err != nil { log.Fatal(err) } fmt.Println(users) }

pgx Go PostgreSQL database mapping rows structs example golang