Overview
This post summarizes Golang interfaces.
What is a Golang Interface?
- A type that enumerates only the types of specific methods.
- A struct that implements all the methods declared in the interface
Foocan be treated as typeFoo. - Interfaces enable polymorphism.
Defining an Interface
Features of Interfaces
Variables of Interface Type
Variables declared as interface type can hold values of any type.
Interface Type as Function Arguments
When an interface type is used as a function argument, values of any type can be passed.
Type Assertion
Syntax for type assertion:
Usage involves two variables:
If the variable i is of type Human, s will hold the actual value of i as type Human, and ok will be true. Otherwise, s will hold the zero value of type Human.
Example of Interface Implementation
An example of a common use case for Golang interfaces: adding shared behavior to different types.
References
- golang.org - Interface types
- Go Language - Empty Interfaces and Type Assertions
- Introduction to Go Language - Interfaces
- Relaxed Go Language Programming Introduction
- Type Casting and Type Conversion with Type Assertion
- Understanding Interface Handling in Go Language
- astaxie/build-web-application-with-golang
- SE Book - Starting Go Language