如何在Go中找到对象的类型? [英] How to find the type of an object in Go?

查看:151
本文介绍了如何在Go中找到对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Go中找到对象的类型?在Python中,我只使用typeof来获取对象的类型.类似地,在Go中,是否可以实现相同的方法?

How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

这是我要迭代的容器:

for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}

在这种情况下,我无法获得对象行的类型,它是字符串数组.

I am not able to get the type of the object lines in this case which is an array of strings.

推荐答案

Go反射包具有检查变量类型的方法.

The Go reflection package has methods for inspecting the type of variables.

以下代码段将打印出字符串,整数和浮点数的反射类型.

The following snippet will print out the reflection type of a string, integer and float.

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

请参阅: http://play.golang.org/p/XQMcUVsOja 进行查看在行动.

see: http://play.golang.org/p/XQMcUVsOja to view it in action.

此处有更多文档: http://golang.org/pkg/reflect/#Type

这篇关于如何在Go中找到对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆