英文:
Access method available to struct used in type declaration
问题
在Go语言中,无法直接访问类型的底层类型中声明的方法。在你的示例代码中,ResourceSet 类型是 Set 类型的别名,但是无法直接调用 Set 类型的 AddId 方法。
如果你想要在 ResourceSet 类型中调用 AddId 方法,一种解决方法是将 ResourceSet 定义为一个结构体,其中包含一个 Set 类型的字段,并在结构体中实现相应的方法。以下是修改后的示例代码:
package main
type Resource struct { 
  Id uint32
}
type Set map[uint32]struct{}
func (s Set) AddId(id uint32) {
  s[id] = struct{}{}
}
type ResourceSet struct {
  set Set
}
func (rs ResourceSet) Add(resource Resource) {
  id := resource.Id
  rs.set.AddId(id)
}
func main() {
  resource := Resource{Id: 1}
  rs := ResourceSet{
    set: make(Set),
  }
  rs.Add(resource)
}
这样,你就可以在 ResourceSet 类型中调用 AddId 方法了。
英文:
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)
答案1
得分: 2
新命名类型的整个目的是拥有一个全新且空的方法集。
嵌入是另一回事,并且为调用嵌入类型的方法添加了一些语法糖。
英文:
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.
答案2
得分: 0
这可以通过使用嵌入来解决:
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)
}
你还可以创建一个初始化构造函数来简化ResourceSet的创建过程:
func NewResourceSet() {
  return ResourceSet{Set{}}
}
func main() {
  s := NewResourceSet()
}
英文:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论