在 Go 中,如何在运行时根据其类型创建结构的新实例? [英] How do you create a new instance of a struct from its type at run time in Go?

查看:19
本文介绍了在 Go 中,如何在运行时根据其类型创建结构的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

为了做到这一点,你需要 reflect.

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)
}

你可以用结构体类型而不是整数来做同样的事情.或者别的什么,真的.当涉及到 map 和 slice 类型时,请务必了解 new 和 make 之间的区别.

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.

这篇关于在 Go 中,如何在运行时根据其类型创建结构的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆