簡単なバージョン
文字列の値に基づいて特定の型の変数を作成するにはどうすればよいでしょうか?
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
に基づいて動的に変数を作成しています。これは、文字列がキーで、型の nil ポインターが値であるマップに各構造体型を登録することによって行われます。
各タイプは、その特定のタイプの新しい変数を返すメソッド 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(`{}`))
}