【发布时间】:2012-06-23 01:43:15
【问题描述】:
简单版
如何根据字符串的值创建某种类型的变量?
type ta struct { a int }
type tb struct { b float }
type tc struct { c string }
t := "tb"
v := MagicVarFunc(t) // Returns a new allocated var of type interface{}
v.(tb).b = 8.3
真实例子
在下面的工作示例中,令人惊讶的是,我正在基于 string 动态创建变量。这是通过在 map 中注册每个结构类型来完成的,其中 string 是键,而 type 的零指针是值。
每个 type 实现一个 interface 方法 New() 返回该特定类型的新变量。
下面的示例非常接近我想要做的,其中每个操作都有一组 JSON 编码数据,这些数据将填充相应的结构。我构建它的方式也是因为我希望能够创建我注册到地图的新的独立操作。
我不确定我现在是否在滥用语言。
如果我完全失去理智,有人可以给我任何指示吗?有没有明显更简单的方法?
package main
import (
"fmt"
"encoding/json"
)
// All I require of an action is that it may be executed
type ActionHandler interface {
Exec()
New() ActionHandler
}
// My list of actions
var mActions = make(map[string]ActionHandler)
// Action Exit (leaving the program)
type aExit struct {}
func (s *aExit) Exec() { fmt.Println("Good bye") }
func (s *aExit) New() ActionHandler { return new(aExit) }
func init() {
var a *aExit
mActions[`exit`] = a
}
// Action Say (say a message to someone)
type aSay struct {
To string
Msg string
}
func (s *aSay) Exec() { fmt.Println(`You say, "` + s.Msg + `" to ` + s.To) }
func (s *aSay) New() ActionHandler { return new(aSay) }
func init() {
var a *aSay
mActions[`say`] = a
}
func inHandler(action string, data []byte) {
a := mActions[action].New()
json.Unmarshal(data, &a)
a.Exec()
}
func main(){
inHandler(`say`, []byte(`{"to":"Sonia","msg":"Please help me!"}`))
inHandler(`exit`, []byte(`{}`))
}
【问题讨论】:
-
新手问题:如果您需要在地图中枚举可用的类,为什么不做一个开关/案例?
-
@Blafasel42 两者都可以。使用 map 并在 init 函数中注册可以让您在不编辑现有代码的情况下添加新类型,允许您通过导入其他包来注册类型。有点像 image 包对 RegisterFormats.
标签: json dynamic types interface go