在 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 执行相同的操作。或者其他什么,真的。当涉及到映射和切片类型时,请务必了解 new 和 make 之间的区别。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)