douzhi1937 2015-07-02 19:05
浏览 3
已采纳

可用于类型声明中的结构的访问方法

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)
  • 写回答

2条回答 默认 最新

  • dongren1977 2015-07-02 20:24
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分