是否可以訪問在類型的基礎類型中聲明的方法?例如,我想要一個ResourceSet
能夠調用我的Set
類型的AddId
方法。可用於類型聲明中結構的訪問方法
參見: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)
}
我得到的錯誤是:
s.AddId undefined (type ResourceSet has no field or method AddId)
好的,這是有用的知道。那麼,那有什麼意義呢?什麼是用例? – Wex
@Wec:用例是:您想要一個帶有特殊方法集的類型,但您可以用另一個指定類型(其方法不需要類型的方法)表示類型狀態。 – Volker