dsfdfdfd6576578 2017-02-20 19:34
浏览 37

如何在Go中将相同方法应用于不同类型?

How to apply same method to different types without repeating code in Go ? I have type1 and type2 and want to apply method Do()

type type1 struct {  }
type type2 struct {  }

I have to repeat code , see below. Go has static typing, so type has to be determined during compile time.

func (p type1) Do() {   }
func (p type2) Do() {   }

This works fine ..but I don't like repeating code

type1.Do()
type2.Do()
  • 写回答

3条回答 默认 最新

  • dongren1977 2017-02-20 19:45
    关注

    It's not clear how the logic goes here, but one common pattern in Go is encapsulating the shared functionality in another struct type and then embed it in your type:

    type sharedFunctionality struct{}
    
    func (*sharedFunctionality) Do() {}
    
    type type1 struct{ sharedFunctionality }
    type type2 struct{ sharedFunctionality }
    

    Now you can call Do() on type1 and type2 instances or in any other type that you need this functionality.

    Edit: based on your comment, you can just redefine some equivalent types such as t1 and t2 that follow the desired protocol (having a Do() method) like this:

    func main() {
        var j job
    
        j = new(t1)
        j.Do()
    
        j = new(t2)
        j.Do()
    }
    
    type job interface {
        Do()
    }
    
    type t1 another.Type1
    
    func (*t1) Do() {}
    
    type t2 yetanother.Type2
    
    func (*t2) Do() {}
    

    Here the types another.Type1 and yetanother.Type2 are not defined by you, but rather some other package designer. But you can do whatever the logic demands with t1 and t2 - as far as public members go or if you are willing to mess with that reflection thing :)

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题