【发布时间】:2021-12-31 06:21:00
【问题描述】:
假设我在包pkg 中定义了一些structs:
package pkg
type Foo struct {
FieldA string
FieldB string
}
type Bar struct {
FieldA string
FieldB string
}
func (Foo) Show() {
fmt.Println("Foo")
}
func (Bar) Show() {
fmt.Println("Bar")
}
type Showable interface {
Show()
}
Registry := map[string]Showable{
//not sure about value type^
"Foo": Foo, // staticcheck shows: not a type
"Bar": Bar, //
}
我想动态地实例化structs;像这样:
package main
import "url/user/pkg"
func main() {
foo := pkg.Registry["Foo"]{
FieldA: "A",
FieldB: "B",
}
bar := pkg.Registry["Bar"]{
FieldA: "X",
FieldB: "Y",
}
foo.Show()
bar.Show()
}
以上显然行不通。
有可能实现吗?我是go 的新手。我看过reflect,我试图用指针构建Registry,空实例的指针,但想不出办法。
最终,我正在尝试编写一个命令行实用程序来更改某些程序的主题。我已经编写了程序特定的方法(如上面示例中的 Show),并且我正在尝试从 config.json 文件中读取程序特定的参数,并动态创建实例。
【问题讨论】:
-
我知道你是如何尝试实现某些东西的,但它显然在 GO 中不起作用。您能否澄清一下您要实施的内容?
-
当然。所以基本上我正在尝试编写一个命令行实用程序来更改某些程序的主题。我已经编写了程序特定的方法(例如上面示例中的
Show),并且我正在尝试从 config.json 文件中读取程序特定的参数,并动态创建实例。
标签: go go struct reflection