The interface type
When you talk to people who have been doing Go for a while, they almost always list the interface as one of their favorite features of the language. The concept of interfaces in Go, similar to other languages, such as Java, is a set of methods that serves as a template to describe behavior. A Go interface, however, is a type specified by the interface{}
literal, which is used to list a set of methods that satisfies the interface. The following example shows the shape
variable being declared as an interface:
var shape interface { area() float64 perim() float64 }
In the previous snippet, the shape
variable is declared and assigned an unnamed type, interface{area()float64; perim()float64}
. Declaring variables with unnamed interface
literal types is not really practical. Using idiomatic Go, an interface
type is almost always declared as a named type
. The previous snippet can be rewritten to use a named interface type, as shown in the following...