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

后端 未结 5 1548
清歌不尽
清歌不尽 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:21

    In order to do that you need reflect.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        // one way is to have a value of the type you want already
        a := 1
        // reflect.New works kind of like the built-in function new
        // We'll get a reflected pointer to a new int value
        intPtr := reflect.New(reflect.TypeOf(a))
        // Just to prove it
        b := intPtr.Elem().Interface().(int)
        // Prints 0
        fmt.Println(b)
    
        // We can also use reflect.New without having a value of the type
        var nilInt *int
        intType := reflect.TypeOf(nilInt).Elem()
        intPtr2 := reflect.New(intType)
        // Same as above
        c := intPtr2.Elem().Interface().(int)
        // Prints 0 again
        fmt.Println(c)
    }
    

    You can do the same thing with a struct type instead of an int. Or anything else, really. Just be sure to know the distinction between new and make when it comes to map and slice types.

提交回复
热议问题