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

后端 未结 5 1541
清歌不尽
清歌不尽 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条回答
  •  粉色の甜心
    2020-12-02 06:12

    Here's a basic example like Evan Shaw gave, but with a struct:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
    
        type Product struct {
            Name  string
            Price string
        }
    
        var product Product
        productType := reflect.TypeOf(product)       // this type of this variable is reflect.Type
        productPointer := reflect.New(productType)   // this type of this variable is reflect.Value. 
        productValue := productPointer.Elem()        // this type of this variable is reflect.Value.
        productInterface := productValue.Interface() // this type of this variable is interface{}
        product2 := productInterface.(Product)       // this type of this variable is product
    
        product2.Name = "Toothbrush"
        product2.Price = "2.50"
    
        fmt.Println(product2.Name)
        fmt.Println(product2.Price)
    
    }
    

    Per newacct's response, using Reflect.zero it would be:

       var product Product
       productType := reflect.TypeOf(product)       // this type of this variable is reflect.Type
       productValue := reflect.Zero(productType)    // this type of this variable is reflect.Value
       productInterface := productValue.Interface() // this type of this variable is interface{}
       product2 := productInterface.(Product)       // the type of this variable is Product
    

    This is a great article on the basics of reflection in go.

提交回复
热议问题