Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active August 31, 2017 03:17
Show Gist options
  • Save icholy/0cd8fad0ba3b3a6c04ae to your computer and use it in GitHub Desktop.
Save icholy/0cd8fad0ba3b3a6c04ae to your computer and use it in GitHub Desktop.

Interfaces

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment