Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Interfaces: a new leaf in an old book

Interfaces: a new leaf in an old book

Using interfaces in Go to write testable code that can be easily modified, or "grows with grace".

Go's interfaces — static, checked at compile time, dynamic when asked for — are, for me, the most exciting part of Go from a language design point of view. If I could export one feature of Go into other languages, it would be interfaces. — Russ Cox

Matt Cottingham

February 02, 2014
Tweet

More Decks by Matt Cottingham

Other Decks in Programming

Transcript

  1. –Russ Cox “Go's interfaces… are, for me, the most exciting

    part of Go from a language design point of view.”
  2. 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
  3. 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
  4. Real-world interfaces • There are some useful examples of interfaces

    in the standard library: • encoding for text and binary representations • Valuer and Scanner interfaces
  5. encoding interface • New in Go 1.2 • Supports Binary

    and Text Marshal/Unmarshal • Used in e.g. Time and IP types
  6. Valuer and Scanner • Database driver needs to convert Go

    types to database types and vice-versa