【问题标题】:How to instantiate struct that is defined in different package from struct name and provide fields如何从结构名称实例化在不同包中定义的结构并提供字段
【发布时间】: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()
}

以上显然行不通。

有可能实现吗?我是 的新手。我看过reflect,我试图用指针构建Registry,空实例的指针,但想不出办法。

最终,我正在尝试编写一个命令行实用程序来更改某些程序的主题。我已经编写了程序特定的方法(如上面示例中的 Show),并且我正在尝试从 config.json 文件中读取程序特定的参数,并动态创建实例。

【问题讨论】:

  • 我知道你是如何尝试实现某些东西的,但它显然在 GO 中不起作用。您能否澄清一下您要实施的内容?
  • 当然。所以基本上我正在尝试编写一个命令行实用程序来更改某些程序的主题。我已经编写了程序特定的方法(例如上面示例中的Show),并且我正在尝试从 config.json 文件中读取程序特定的参数,并动态创建实例。

标签: go go struct reflection


【解决方案1】:

如果我正确理解您想要达到的目标,这里是 这样做的方法:

registry.go:

package pkg

import (
    "fmt"
    "io"
)

type NewShowable func(r io.Reader) Showable

type Showable interface {
    Show()
}

type Foo struct {
    FieldA string
    FieldB string
}

func newFoo(r io.Reader) Showable {
    // Read config from r and construct Foo
    return Foo{}
}

func (Foo) Show() {
    fmt.Println("Foo")
}

type Bar struct {
    FieldA string
    FieldB string
}

func newBar(r io.Reader) Showable {
    // Read config from r and construct Bar
    return Bar{}
}

func (Bar) Show() {
    fmt.Println("Bar")
}

var Registry = map[string]NewShowable{
    "Foo": newFoo,
    "Bar": newBar,
}

main.go:

package main

import (
    "log"
    "os"

    "url/user/pkg"
)

func main() {
    f, err := os.Open("config.json")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()
    foo := pkg.Registry["Foo"](f)

    f2, err := os.Open("config2.json")
    if err != nil {
        log.Fatalln(err)
    }
    defer f2.Close()
    bar := pkg.Registry["Bar"](f2)
    foo.Show()
    bar.Show()
}

【讨论】:

  • 这正是我想要的!谢谢!顺便说一句,你会说这是对go 的坏模式吗?
  • 我没有看到任何险恶的地方。标准库使用类似的注册表。例如,“sql”包使用一个注册表,允许第三方包添加他们命名的 SQL 驱动程序:cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/database/…
  • 也就是说,如果您期望某些第三方软件包可以扩展注册表,那么这种方法是有意义的。否则,我还没有看到其中的价值。
猜你喜欢
  • 2016-10-21
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多