Instance new Type (Golang)

后端 未结 2 1328
一整个雨季
一整个雨季 2020-11-29 05:31

Can anyone tell me how to create a new instance of Type from a string? Reflect?

There are examples but they are for the older (pre Go 1 versions) of the language [:(

2条回答
  •  我在风中等你
    2020-11-29 06:03

    Factory with predefined constructors can be based on something like:

    package main
    
    import (
        "fmt"
    )
    
    type Creator func() interface{}
    
    type A struct {
        a int
    }
    
    type B struct {
        a bool
    }
    
    func NewA() interface{} {
        return new(A)
    }
    
    func NewB() interface{} {
        return new(B)
    }
    
    func main() {
        m := map[string]Creator{}
        m["A"] = NewA
        m["B"] = NewB
        for k, v := range m {
            fmt.Printf("%v -> %v\n", k, v())
        }
    }
    

提交回复
热议问题