dsfasdfsda234234 2013-06-12 23:30
浏览 35
已采纳

指向实现同一接口的不同结构的指针数组

What I am trying to do: I have several struct types, all implementing the same interface, which declare a method, say "Process()"

type Worker interface {
  Process()
}

type obj1 struct {
}

func (o *obj1) Process() {
}

// same with struct type obj2, obj3, ...

Throughout the code, I create several instances of these structs, and then I want to call the process on each of these. Calling Process() on each works fine.

o1 := obj1.New()
o2 := obj1.New()
o3 := obj2.New()
o4 := obj3.New()
// ...
o1.Process()
o2.Process()
// ...

Now, I would like to have a "ProcessAll()" function, that would receive those instances and do the job of calling the Process() method on each of those, as well as some meta work around it.

Here is the sort of code that I'm trying to produce, but this particular snippet does not work because I'm not sure how to do it:

func ProcessAll(objs []*Worker) {
   for _, obj := range objs {
     obj.Process()
   }
}

ProcessAll([]*Worker{o1, o2, /* ... */})

Is that sort of things possible to accomplish with go, and if yes how can I do to implement it ?

  • 写回答

1条回答 默认 最新

  • dougu4704 2013-06-12 23:35
    关注

    You don't need to make objs array of pointers to interface. Interfaces are reference values.

    package main
    
    import "fmt"
    
    type Worker interface{
        Process()
    }
    
    type obj1 struct {
    }
    
    func (o *obj1) Process() {
        fmt.Println("obj1 Process()")
    }
    
    type obj2 struct {
    }
    
    func (o *obj2) Process() {
        fmt.Println("obj2 Process()")
    }
    
    func ProcessAll(objs []Worker) {
        for _, o := range objs {
            o.Process()
        }
    }
    
    func main() {
        ProcessAll([]Worker{ &obj1{}, &obj2{} })
    }
    

    Or check it out here: http://play.golang.org/p/eWXiZzrN-W

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

报告相同问题?

悬赏问题

  • ¥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时遇到的编译问题