Is it possible to access methods that are declared in a type's underlying type? For example, I want a ResourceSet
to be able to call my Set
type's AddId
method .
See: http://play.golang.org/p/Fcg6Ryzb67
package main
type Resource struct {
Id uint32
}
type Set map[uint32]struct{}
func (s Set) AddId(id uint32) {
s[id] = struct{}{}
}
type ResourceSet Set
func (s ResourceSet) Add(resource Resource) {
id := resource.Id
s.AddId(id)
}
func main() {
resource := Resource{Id: 1}
s := ResourceSet{}
s.Add(resource)
}
The error I'm getting is:
s.AddId undefined (type ResourceSet has no field or method AddId)
The whole point of a new named type is to have a fresh and empty method set.
Embedding is a different story and add some syntactical sugar to call methods of embedded types.
This can be solved using embedding:
type ResourceSet struct {
Set
}
func (s ResourceSet) Add(resource Resource) {
id := resource.Id
s.AddId(id)
}
func main() {
resource := Resource{Id: 1}
s := ResourceSet{Set{}}
s.Add(resource)
}
You can also create an initializing constructor to make the ResourceSet
creation process simpler:
func NewResourceSet() {
return ResourceSet{Set{}}
}
func main() {
s := NewResourceSet()
}