gpt4 book ai didi

reflection - 我们如何使用空接口(interface)指向的实际类型在 Go 中创建该类型的新实例?

转载 作者:IT王子 更新时间:2023-10-29 02:23:21 26 4
gpt4 key购买 nike

请检查以下程序。 Var zinterface{} 类型。它存储结构 X 的类型。但我不能用它来创建 X 的新实例。我有一些要求,我需要将对象的类型保存在 interface{} 变量中,并使用它来创建该类型的实例。这是一个link for the snippet on go playground

package main

import (
"fmt"
"reflect"
)

type X struct {
a int
b int
}

type MyInt int

func main() {
x := X{}
y := reflect.TypeOf(x)
fmt.Printf("%v\n", reflect.New(y))

var z interface{}
z = y
fmt.Printf("%v\n", z) // prints main.X

//Below line throws the error
fmt.Printf("%v\n", reflect.New(z)) //----> This line throws error

}

最佳答案

您可以使用 type assertioninterface{} 值中提取 reflect.Type 值:

fmt.Printf("%v\n", reflect.New(z.(reflect.Type))) //----> Works!

您在 Go Playground 上修改的示例.

请注意,如果 z 不包含 reflect.Type 类型的值或者它是 nil,则上面的示例会发生困惑。您可以使用特殊的逗号-ok 形式来防止这种情况:

if t, ok := z.(reflect.Type); ok {
fmt.Printf("%v\n", reflect.New(t)) // t is of type reflect.Type
} else {
fmt.Println("Not the expected type or nil!")
}

关于reflection - 我们如何使用空接口(interface)指向的实际类型在 Go 中创建该类型的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36418582/

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