Riyaz Mansoor
Riyaz Mansoor

Reputation: 715

Go Golang - embedding types and "len/range"

package m
type M map[int]int
// have methods on M
// can use len and range on M

package n
// need methods of M
type N struct { M }
// methods available
// BUT cannot use len or range on N
// if " type N M " - I lose the methods on M

Need the methods of M and len/range functionality in a different package. How can this be done ?

Upvotes: 1

Views: 562

Answers (1)

Marc
Marc

Reputation: 21145

Ignoring packages (they don't matter in this scenario), you need to specify a valid type for the builtins len and range:

type M map[int]int

func (m *M) SayHi() {
    fmt.Println("Hi!")
}

type N struct{ M }

func main() {
    var foo N
    fmt.Println(len(foo.M))
    for k, v := range foo.M {
        fmt.Printf("%d: %d\n", k, v)
    }
    foo.SayHi()
}

foo.SayHi() works because SayHi is promoted to struct N.

However, len and range are not methods on M, they are builtins that expect specific types. Embedding does not change the type, it promotes methods from the embedded field to the container struct.

You can read more about the details in the Go spec and Effective Go.

Upvotes: 2

Related Questions