Skip to content

Instantly share code, notes, and snippets.

@coyle
Created June 29, 2018 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coyle/7c6991b712796e6357ea1f828f332b3f to your computer and use it in GitHub Desktop.
Save coyle/7c6991b712796e6357ea1f828f332b3f to your computer and use it in GitHub Desktop.
+ satisfied implicitly
+ don't need to decalre, having the necessary methods is enough
1. interfaces as contracts
- Abstract type
- doesn't expose the representation or internal structure of it's values or the set of basic operations the support
- Only reveals a subset of methods
- Know nothing about what it is only what it can do (what behaviors are provided by their methods)
- Fprintf / substitutability
- https://golang.org/pkg/fmt/#Fprintf
- https://golang.org/pkg/fmt/#Printf
- https://golang.org/pkg/io/#Writer
- https://play.golang.com/p/ZVqCREw82Fk
- https://golang.org/pkg/fmt/#Stringer
1. Interface Types
- specifies a set of methods that a concrete type must possess to be considered an instance of that interface
- https://golang.org/pkg/io/#Reader
- https://golang.org/pkg/io/#Writer
- https://golang.org/pkg/io/#ReadWriter
- order is inmaterial
- could have written it out
- or mixed it
1. Interface Satisfaction
- a type satisifies an interface if it posseses all the methods the interface requires.
- os.File satisfies, Reader, Writer, Closer and ReadWriter
- https://golang.org/pkg/os/#File
- bytes.Buffer satisfies Reader, Writer and ReadWriter but not Closer.
- as shorthand, typically say that the concrete type "is a" particular interface type. meaning it satisfies the interface type.
- i.e. a bytes.Buffer is an io.Writer and os.File is an io.ReadWriter
- empty interface type -- interface{} places no demands on the types that satisfy it. Can assign any value to the empty interface
- https://play.golang.com/p/wZubbv4Pk-4
1. Type Assertions
- is an operation applied to an interface value
- syntactically x.(T)
- where x is an expression of an interface type and T is a type ("asserted type")
- if the check fails it panics
- https://play.golang.com/p/kitg_vxFbuC
- Two possibilities:
- if T is a concrete type then the type assertion checks x's dynamic type is identical to T, if this succeeds then the result is the concrete type.
- if T is an interface type, then the type assertion checks whether x's dynamic type satisifies T, if the check succeeds the dynamic value is not extracted the result is the interface value.
1. Type switches
- https://play.golang.com/p/xEiADYnCtkC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment