dsgdhtr_43654 2016-04-18 02:42 采纳率: 100%
浏览 18
已采纳

是否可以存储Go类型

I've got a handful of interfaces, and n number of structs that arbitrarily implement these interfaces. I'd like to keep an array of types and be able to run a loop over them to see which ones are implemented. Is it possible to store a type like this? I spent a little bit of time with the reflect package, but couldn't really find what I was looking for, I understand if maybe this isn't best practice. Trying to do something similar to this.. without a giant type switch, fallthrough, or if.. if... if.

type InterOne interface {
    InterOneMethod() string
}

var interfaceMap = map[string]type {
    "One": InterOne,
    ...
}

func doesHandle(any interface{}) []string {
    var handles []string
    for k, v := range interfaceMap {
      if _, ok := any.(v); ok {
          handles = append(handles, k)
      }
    }
    return handles
}

EDIT: The answer marked as correct is technically right. I found that due to the comment about the method calling & the overuse of reflection, that this approach was a bad idea. Instead I went with a type switch to check for a single interface because fallthrough is not supported on type switch, and a large if.. if.. if.. with type assertions to be able to make the appropriate calls.

  • 写回答

1条回答 默认 最新

  • duanqianwei2485 2016-04-18 02:56
    关注

    You can use reflect, notice that to get the type of an interface the only way is to use reflect.TypeOf((*INTERFACE)(nil)).Elem(), here's a working example:

    var interfaceMap = map[string]reflect.Type{
        "One": reflect.TypeOf((*InterOne)(nil)).Elem(),
    ....
    }
    
    func doesHandle(any interface{}) []string {
        t := reflect.TypeOf(any)
        var handles []string
        for k, v := range interfaceMap {
            if t.Implements(v) {
                handles = append(handles, k)
            }
        }
        return handles
    }
    

    <kbd>playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题