Search code examples
goreflectiongo-reflect

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


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?

I am trying to do lazy instantiation to save memory.


Solution

  • 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.