假設我struct在 package 中定義了一些s pkg:
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, //
}
我想struct動態實體化s;像這樣:
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 檔案中讀取特定于程式的引數,并動態創建實體。
uj5u.com熱心網友回復:
如果我正確理解您要實作的目標,則可以采用以下方法:
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()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400770.html
下一篇:分配給介面的指標
