小编典典

您如何在Go运行时根据其类型创建结构的新实例?

go

在Go中,如何在运行时根据对象的类型创建对象的实例?我想您还需type要先获取对象的实际值吗?

我正在尝试执行惰性实例化以节省内存。


阅读 361

收藏
2020-07-02

共1个答案

小编典典

为了做到这一点,你需要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)
}

您可以使用结构类型(而不是int)执行相同的操作。还是其他的,真的。只需确保了解map和slice类型时new和make之间的区别即可。

2020-07-02