doukuipei9938 2013-03-04 01:13
浏览 28
已采纳

Go —如何处理结构类型之间的公共字段

If I have two types:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}

Is there any way to achieve the following without needing two methods, given that both access identically-named fields and return the sum of them?

func (a *A) Sum() int {
     return a.X + a.Y
}

func (b *B) Sum() int {
     return b.X + b.Y
}

Of course, were X and Y methods, I could define an interface containing these two methods. Is there an analogue for fields?

  • 写回答

1条回答 默认 最新

  • dousi6405 2013-03-04 01:18
    关注

    Embed A in B.

    type A struct {
          X int
          Y int
    }
    
    func (a *A) Sum() int {
         return a.X + a.Y
    }
    
    type B struct {
          *A
          Z int 
    }
    
    a := &A{1,2}
    b := &B{&A{3,4},5}
    
    fmt.Println(a.Sum(), b.Sum()) // 3 7
    

    http://play.golang.org/p/fjT9c-m_Lj

    But no, there's no interface for fields. Only methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?