Interfaces

Implicit interfaces, polymorphism, Stringer, the empty interface and type switches.

An interface in Go is a set of methods. A type satisfies it simply by having those methods — there is no implements keyword. This makes small interfaces (io.Reader, io.Writer, fmt.Stringer, error) the glue of the whole standard library.

Sensors behind an interface

Thermistor and Accelerometer satisfy Sensor because they have Name and Read methods.

report works with any Sensor.

A String() method makes fmt print a type your way (fmt.Stringer).

any (= interface{}) holds any value; a type switch dispatches on the dynamic type.

s.(Accelerometer) with comma-ok checks and extracts the concrete type.

Design advice

func find() error { var e *MyErr = nil; return e } // != nil!

func find() error { return nil } Returning a nil pointer of a concrete type gives an interface holding (type *MyErr, nil), which is not equal to nil. Return the literal nil.

How does a type implement an interface in Go?

Implicitly, by having all of the interface's methods with matching signatures.