作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
这是我的例子: 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/
我是一名优秀的程序员,十分优秀!