【发布时间】:2018-02-07 08:36:19
【问题描述】:
我现在正在学习 Go,我编写了一个小项目,其中包含一些向内部日志报告的探针。我有一个基本探针,我想创建新的探针来扩展基本探针。
我想将对象保存在数组/切片 LoadedProbes 中。
type LoadableProbe struct {
Name string
Probe Probe
Active bool
}
var LoadableProbes []LoadableProbe
基本的探测结构是:
type ProbeModule struct {
version VersionStruct
name string
author string
log []internals.ProbeLog
lastcall time.Time
active bool
}
func (m *ProbeModule) New(name string, jconf JsonConfig) {
// read jsonConfig
}
func (m *ProbeModule) Exec() bool {
// do some stuff
return true
}
func (m *ProbeModule) String() string {
return m.name + " from " + m.author
}
func (m *ProbeModule) GetLogCount() int {
return len(m.log)
}
[...]
我正在将此基本结构用于其他探针,例如:
type ShellProbe struct {
ProbeModule
}
func (s *ShellProbe) New(name string, jconf JsonConfig) {
s.ProbeModule.New(name, jconf)
fmt.Println("Hello from the shell")
}
func (s *ShellProbe) Exec() bool {
// do other stuff
return true
}
在 Init() 期间,我调用以下代码:
func init() {
RegisterProbe("ShellProbe", ShellProbe{}, true)
}
func RegisterProbe(name string, probe Probe, state bool) {
LoadableProbes = append(LoadableProbes, LoadableProbe{name, probe, state})
}
现在的问题是我无法将 Shellprobe 类型添加到 LoadableProbe 结构,它需要一个 Probe 结构。
我的想法是使用 interface{} 代替 Loadable Probe 结构中的 Probe 结构。但是当我调用 Probe 对象的 New() 方法时:
for _, p := range probes.LoadableProbes {
probe.Probe.New(probe.Name, jconf)
}
但我得到了错误:p.Probe.New undefined (type interface {} is interface with no methods)
我该如何解决这个问题?
【问题讨论】:
-
您没有分享您对 Probe 类型的定义。如果您添加它,答案可能会更具体。
-
“我想创建新的探针来扩展基本探针” - 停在那里。你不能在 Go 中“扩展”; Go 没有继承。如果你这样想,你将创建一个与 Go 根本不兼容的设计;您会发现自己以不寻常的方式滥用构图并造成无法维护的混乱。在尝试像这样的复杂设计之前,我强烈建议您阅读 Go 接口、它们的工作原理以及它们的使用方式。