如何确定界面{}值的“真实”类型? [英] How to determine an interface{} value's "real" type?
本文介绍了如何确定界面{}值的“真实”类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我还没有找到使用 interface {}
类型的好资源。例如
包主
$ b $导入fmt
func weirdFunc (i int)interface {} {
if i == 0 {
returnzero
}
return
}
func main() {
var i = 5
var w = weirdFunc(5)
//这个例子有效!
if tmp,ok:= w。(int); OK {
i + = tmp
}
fmt.Println(i =,i)
}
您是否知道使用Go的 interface {}
?
具体问题:
- 如何获得真实w类型?
- 是否有任何方法可以获取某个类型的字符串表示形式?
- 是否有任何方式将字符串表示形式用于
convert a值?
解决方案
您的示例确实有效。
包主
导入fmt
func怪异(i int)interface {} {
if i< 0 {
returnnegative
}
return
func main(){
var i = 42
如果w,ok:=怪异(7)。(int); OK {
i + = w
}
if w,ok:= weird(-100)。(int); OK {
i + = w
}
fmt.Println(i =,i)
}
产出:
i = 49
它使用键入断言。
I have not found a good resource for using interface{}
types. For example
package main
import "fmt"
func weirdFunc(i int) interface{} {
if i == 0 {
return "zero"
}
return i
}
func main() {
var i = 5
var w = weirdFunc(5)
// this example works!
if tmp, ok := w.(int); ok {
i += tmp
}
fmt.Println("i =", i)
}
Do you know of a good introduction to using Go's interface{}
?
specific questions:
- how do I get the "real" Type of w?
- is there any way to get the string representation of a type?
- is there any way to use the string representation of a type to convert a value?
解决方案
Your example does work. Here's a simplified version.
package main
import "fmt"
func weird(i int) interface{} {
if i < 0 {
return "negative"
}
return i
}
func main() {
var i = 42
if w, ok := weird(7).(int); ok {
i += w
}
if w, ok := weird(-100).(int); ok {
i += w
}
fmt.Println("i =", i)
}
Output:
i = 49
It uses Type assertions.
这篇关于如何确定界面{}值的“真实”类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文