问题描述
Go 反射包具有检查变量类型的方法。
以下代码段将打印出字符串、整数和浮点数的反射类型。
package main
import (
"fmt"
"reflect"
)
func main() {
tst := "string"
tst2 := 10
tst3 := 1.2
fmt.Println(reflect.TypeOf(tst))
fmt.Println(reflect.TypeOf(tst2))
fmt.Println(reflect.TypeOf(tst3))
}
输出:
Hello, playground
string
int
float64
我找到了 3 种在运行时返回变量类型的方法:
使用字符串格式
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
使用反射包
func typeof(v interface{}) string {
return reflect.TypeOf(v).String()
}
使用类型断言
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case float64:
return "float64"
//... etc
default:
return "unknown"
}
}
每种方法都有不同的最佳用例:
字符串格式 - 短而低的占用空间(不需要导入反射包)
反射包 - 当需要有关我们可以访问完整反射功能的类型的更多详细信息时
类型断言 - 允许分组类型,例如将所有 int32、int64、uint32、uint64 类型识别为“int”
解决方法
如何在 Go 中找到对象的类型?在 Python 中,我只是typeof
用来获取对象的类型。同样在 Go 中,有没有办法实现相同的?
这是我正在迭代的容器:
for e := dlist.Front(); e != nil; e = e.Next() {
lines := e.Value
fmt.Printf(reflect.TypeOf(lines))
}
在这种情况下,我无法获得对象行的类型,即字符串数组。