Interfaces
A new leaf in an old book
Matthew Cottingham
[email protected]
@mattrco
Slide 2
Slide 2 text
whoami
Then: web services,
ETLs, messaging.
Now: forum software,
web services all Go
Slide 3
Slide 3 text
–Russ Cox
“Go's interfaces… are, for me, the
most exciting part of Go from a
language design point of view.”
Slide 4
Slide 4 text
Recap
Slide 5
Slide 5 text
Stringer
Slide 6
Slide 6 text
Implicitly satisfied interfaces
• In order to satisfy an interface, we just need to
implement the right functions
• So it’s easy decouple components even if they’re
third party or part of the standard library
Slide 7
Slide 7 text
Decoupling database/sql
• sql.DB is a struct type which makes it harder to
switch out for a test implementation
• Create an interface type (I called it DBer) with
same methodset as sql.DB
• Replace instances of sql.DB with interface DBer
Slide 8
Slide 8 text
DBer interface type
Slide 9
Slide 9 text
DBer usage
Slide 10
Slide 10 text
Other options
• https://github.com/erikstmartin/go-testdb
• also, fakedb (internal test package) implements
the Driver interface
Slide 11
Slide 11 text
Real-world interfaces
• There are some useful examples of interfaces in
the standard library:
• encoding for text and binary representations
• Valuer and Scanner interfaces
Slide 12
Slide 12 text
encoding interface
• New in Go 1.2
• Supports Binary and Text Marshal/Unmarshal
• Used in e.g. Time and IP types
Slide 13
Slide 13 text
(Un)MarshalText
Slide 14
Slide 14 text
net.IP implementation
Slide 15
Slide 15 text
Valuer and Scanner
• Database driver needs to convert Go types to
database types and vice-versa
Slide 16
Slide 16 text
PostgreSQL hstore
Slide 17
Slide 17 text
Analysis
• go oracle can tell you (among other things)