Let's imagine a very simple table
CREATE TABLE people {
id bigserial,
name character varying
}
With a simple structure that we can map the data to
type Person struct {
Id int64
Name string
}
Here is an example of using Go's implicit interfaces to reuse code.
// both sql.Row and sql.Rows implement Scanner
type Scanner interface{
func Scan(...interface{}) error
}
func ScanPerson(s Scanner) (*Person, error) {
p := &Person{}
err := s.Scan(&p.Id, &p.Name)
return p, err
}
Now we can use these methods with both sql.Row and sql.Rows
.
r := db.QueryRow("SELECT * FROM people LIMIT 1")
p, _ := ScanPerson(r)
var people []*Person
r, _ := db.Query("SELECT * FROM people")
for r.Next() {
p, _ := ScanPerson(r)
people = append(people, p)
}