The following interface defines a set of methods to be implemented by mooing objects:
type Mooing interface {
Moo() string
}
The following defines a set of methods to be implemented by grazing objects:
type Grazing interface {
EatGrass()
}
I have a function that operates on cows:
func Milk(cow *Cow)
It doesn't have to be a cow, though--anything that conforms to Mooing
and Grazing
is close enough. In Go, is it possible to specify a parameter of Mooing and Grazing
? In pseudocode, something like the following?
func Milk(cow {Mooing, Grazing})
In other words, only parameters that satisfy both of these interfaces will be accepted.
An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.
Like a struct an interface is created using the type keyword, followed by a name and the keyword interface . But instead of defining fields, we define a “method set”. A method set is a list of methods that a type must have in order to “implement” the interface.
To implement an interface in Go, you need to implement all the methods declared in the interface. Go Interfaces are implemented implicitly. Unlike Java, you don't need to explicitly specify using the implements keyword.
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
You can compose interfaces in Go as follows:
type MooingAndGrazing interface {
Mooing
Grazing
}
If you don't want to declare a new named type, you could inline this as:
func Milk(cow interface{Mooing; Grazing})
You can experiment with this example here: http://play.golang.org/p/xAODkd85Zq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With