How do you create a new instance of a struct from its type at run time in Go?

后端 未结 5 1532
清歌不尽
清歌不尽 2020-12-02 06:07

In Go, how do you create the instance of an object from its type at run time? I suppose you would also need to get the actual type of the object first too?

5条回答
  •  -上瘾入骨i
    2020-12-02 06:32

    You don't need reflect and you can do this easy with factory pattern if they share the same interface:

    package main
    
    import (
        "fmt"
    )
    
    // Interface common for all classes
    type MainInterface interface {
        GetId() string
    }
    
    // First type of object
    type FirstType struct {
        Id string
    }
    
    func (ft *FirstType) GetId() string {
        return ft.Id
    }
    
    // FirstType factory
    func InitializeFirstType(id string) MainInterface {
        return &FirstType{Id: id}
    }
    
    
    // Second type of object
    type SecondType struct {
        Id string
    }
    
    func (st *SecondType) GetId() string {
        return st.Id
    }
    
    // SecondType factory
    func InitializeSecondType(id string) MainInterface {
        return &SecondType{Id: id}
    }
    
    
    func main() {
        // Map of strings to factories
        classes := map[string]func(string) MainInterface{
            "first": InitializeFirstType,
            "second": InitializeSecondType,
        }
    
        // Create a new FirstType object with value of 10 using the factory
        newObject := classes["first"]("10")
    
        // Show that we have the object correctly created
        fmt.Printf("%v\n", newObject.GetId())
    
    
        // Create a new SecondType object with value of 20 using the factory
        newObject2 := classes["second"]("20")
    
        // Show that we have the object correctly created
        fmt.Printf("%v\n", newObject2.GetId())
    }
    

提交回复
热议问题