gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:58:18 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com