Frage

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.

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top