0

I come across this code in Go:

type Mytype struct {
  Interfacename
  var1  ClientInterface1
  var2  ClientInterface2
  id    int
}

What does that first field mean?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jamesszm
  • 101
  • 1
  • 10

1 Answers1

2

Mostly, this is how some sort of inheritance (by composition rather than inheritance) is achieved in go. Check this out: https://golang.org/doc/effective_go.html#embedding

This will grant the Outer type (MyType) access to this inner type's Receiver methods (the assigned struct{} since this is an interface).

From Go Effective:

There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one

Thanks @Flimzy and @md2perpe

Also, this defines an anonymous field, for which the variable name will be the same as its type name.

alexbt
  • 16,415
  • 6
  • 78
  • 87