如何在Go中查找对象类型? 在Python中,我只需使用typeof
获取对象的类型。同样,在Go中,是否有一种实现方式可以实现相同的功能?
这是我正在遍历的容器:
for e := dlist.Front(); e != nil; e = e.Next() {
lines := e.Value
fmt.Printf(reflect.TypeOf(lines))
}
在这种情况下,我无法获得对象“lines”的类型,该对象是一个字符串数组。
如何在Go中查找对象类型? 在Python中,我只需使用typeof
获取对象的类型。同样,在Go中,是否有一种实现方式可以实现相同的功能?
这是我正在遍历的容器:
for e := dlist.Front(); e != nil; e = e.Next() {
lines := e.Value
fmt.Printf(reflect.TypeOf(lines))
}
在这种情况下,我无法获得对象“lines”的类型,该对象是一个字符串数组。
Type.Elem()
:a := []string{"foo", "bar", "baz"}
fmt.Println(reflect.TypeOf(a).Elem())
如果你想在if
表达式中检测类型:
if str, ok := myvar.(string); ok {
print("It's a string")
}
或者不使用类型断言(可能会产生错误):
if reflect.TypeOf(myvar).String() == "string" {
print("It's a string")
}
package _test
import (
"fmt"
"reflect"
"testing"
)
func TestType(t *testing.T) {
type Person struct {
name string
}
var i interface{}
i = &Person{"Carson"}
for idx, d := range []struct {
actual interface{}
expected interface{}
}{
{fmt.Sprintf("%T", "Hello") == "string", true},
{reflect.TypeOf("string").String() == "string", true},
{reflect.TypeOf("string").Kind() == reflect.String, true},
{reflect.TypeOf(10).String() == "int", true},
{reflect.TypeOf(10).Kind() == reflect.Int, true},
{fmt.Sprintf("%T", 1.2) == "float64", true},
{reflect.TypeOf(1.2).String() == "float64", true},
{reflect.TypeOf(1.2).Kind() == reflect.Float64, true},
{reflect.TypeOf([]byte{3}).String() == "[]uint8", true},
{reflect.TypeOf([]byte{3}).Kind() == reflect.Slice, true},
{reflect.TypeOf([]int8{3}).String() == "[]int8", true},
{reflect.TypeOf([]int8{3}).Kind() == reflect.Slice, true},
{reflect.TypeOf(Person{"carson"}).Kind() == reflect.Struct, true},
{reflect.TypeOf(&Person{"carson"}).Kind() == reflect.Ptr, true},
{fmt.Sprintf("%v", i.(*Person)) == "&{Carson}", true},
{fmt.Sprintf("%+v", i.(*Person)) == "&{name:Carson}", true},
} {
if d.actual != d.expected {
t.Fatalf("%d | %s", idx, d.actual)
}
}
}
interface{}..(type)
,就像在playground中所示。package main
import "fmt"
func main(){
types := []interface{} {"a",6,6.0,true}
for _,v := range types{
fmt.Printf("%T\n",v)
switch v.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v.(int) * 2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v.(string)))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
}
switch v := v.(type)
,然后这样做:case int: fmt.Printf("Twice %v is %v\n", v, v * 2)
和 case string: fmt.Printf("%q is %v bytes long\n", v, len(v))
。在 switch 语句中,内部的 v
变量会遮盖原始的 v
,因此在 case 代码块内,v
被视为指定在 case 语句中的变量类型。 - Arkemlar你可以使用reflect.TypeOf
。
int
,string
):它将返回其名称(例如:int
,string
)<包名>.<结构体名>
的内容(例如:main.test
)
fmt.Printf("%T\n", var)
- meh