Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a composite interface in Go?

Tags:

interface

go

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.

like image 931
modocache Avatar asked May 08 '14 04:05

modocache


People also ask

How do you declare an interface type in Golang?

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.

How do you declare a struct interface?

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.

How are interfaces implemented in Go?

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.

What does interface {} mean in Golang?

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.


1 Answers

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

like image 100
James Henstridge Avatar answered Oct 05 '22 06:10

James Henstridge