dongxie7683 2014-05-09 05:13
浏览 62
已采纳

Golang-扫描某种类型的所有结构

I am a beginner in Go. I maybe thinking too traditional coming from years in other languages, but here is what I want to do in Go. Assume the following use case

  1. I have interface I. This interface has functions, start() and stop()
  2. There are many structs implementing the interface. struct A, struct B, struct C
  3. When the application starts, I want to call start() on structs A, B and C
  4. Similarly, when the application terminates, I want to call stop() on the A, B, C structs.
  5. I do not want to hard code struct A, B and C anywhere in the code to call the start/stop functions. This is so that when I add struct D later (also implements interface I), the code will automatically work without modification.
  6. In order to achieve this, I need to be able to say "Hey Go, give me all the types that implement interface I".
  7. If I get back a slice of A, B and C, I can simply loop through and call the right methods at the right time.

Doable in Go?

  • 写回答

1条回答 默认 最新

  • dtdh11647 2014-05-09 05:36
    关注

    The short answer is: No, that is not doable

    Go is a strictly typed language. This allows the linker to leave out type definitions, methods and functions not used by the application.

    That means, unless a type (such as struct A) are referenced and used somewhere, it will be omitted.

    But in your comment, you mentioned you don't want the types but rather the currently existing instances of any type that implements the interface.

    This is not possible either.

    Alternative

    My suggestion is to create a global map (or slice):

    var instMap = map[string]StartStopper
    

    And have each struct add an instance to that map with an init function that will automatically be called at the start of the application:

    type A struct {}
    
    func init() {
        instMap["A"] = new(A)
    }
    

    Then when you want to start all the instances, just iterate over the map and call Start()

    Edit

    And if it is not a one-instance-per-type situation but rather multiple instances for each type, then you will have to add to the map (or slice) whenever a new instance is created. And you would have to remember deleting the instance from the map when it is not to be used anymore, or else it won't be handled by the Garbage Collector.

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大