gpt4 book ai didi

reflection - 如何在 Golang 运行时动态转换类型?

转载 作者:IT王子 更新时间:2023-10-29 02:27:56 28 4
gpt4 key购买 nike

这是我的例子: http://play.golang.org/p/D608cYqtO5

基本上我想这样做:

theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)

最佳答案

符号

value.(type)

被称为type-assertion .断言中的 type 必须在编译时已知,并且它始终是类型名称。

在您的 playground 示例中,SetStruct2 可以使用 type-switch为它的第二个参数处理不同的类型:

switch v := value.(type) {
case Config:
// code that uses v as a Config
case int:
// code that uses v as an int
}

但是,您不能断言接口(interface)是动态的(就像在您的代码中一样)。因为否则编译器无法对您的程序进行类型检查。

编辑:

I don't want to case them one by one if there is another way to do so?

您可以使用 reflection与类型无关地工作。然后你可以在值上随机设置东西,但如果你对一个类型执行非法操作它会 panic 。

如果您想从编译器的类型检查中获益,则必须列举不同的情况。

关于reflection - 如何在 Golang 运行时动态转换类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207232/

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