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

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

问题描述

在Go中,如何在运行时从其类型创建对象的实例?我想你还需要首先获得对象的实际类型



我正在尝试lazy instantiation来节省内存。

解决方案

为了做到这一点,您需要 reflect

 包主

导入(
fmt
反映


func main(){
//一种方法是获得所需类型的值
a:= 1
// reflect.New工程有点像内置函数new
//我们将得到一个反射指针到一个新的int值
intPtr:= reflect.New(reflect.TypeOf(a ))
//只是为了证明它
b:= intPtr.Elem().interface()。(int)
//打印0
fmt.Println(b)

//我们也可以使用reflect.New而不具有
类型的值var nilInt * int
intType:= reflect.TypeOf(nilInt).Elem()
intPtr2:= reflect.New(intType)
//同上
c:= intPtr2.Elem().interface()。(int)
//再次打印0
fmt.Println(c)
}

你可以用struct类型而不是int来做同样的事情。或者其他任何东西,真的。只要确定了解map和slice类型时new和make之间的区别即可。


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.

解决方案

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.

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

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