go - 在 Go 中,如何在运行时从其类型创建一个新的结构实例?

标签 go reflection go-reflect

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

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

最佳答案

为此,您需要 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 之间的区别。

关于go - 在 Go 中,如何在运行时从其类型创建一个新的结构实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850140/

相关文章:

pointers - 解析指针

android - 如何注入(inject)screen_on事件? (不适用于初学者)

go - 在 golang 中,是否可以从类型本身获取 reflect.Type,从名称作为字符串?

http - 为什么 Golang http.ResponseWriter 执行被延迟?

go - json.Unmarshal 在进行 curl 调用时不填充结构

Java 相当于 Knockout.js 计算可观察量?

go - 如何检查对象是否具有特定方法?

go - 按名称访问结构属性

generics - 在go中获取不同属性的通用函数

c# - 获取扩展方法中第一个参数的名称?