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

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

问题描述

我如何在Golang中找到对象的类型?在Python中,我只是使用 typeof 来获取对象的类型。同样在Go中,是否有一种方法可以实现它?



以下是我正在迭代的容器:

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

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

解决方案

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



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

 包主要

导入(
fmt
反映


func main(){

tst:=string
tst2:= 10
tst3:= 1.2

fmt.Println(reflect.TypeOf(tst))
fmt.Println(reflect.TypeOf(tst2))
fmt.Println(reflect.TypeOf(tst3))

}

请参阅: http://play.golang.org/p / XQMcUVsOja 来查看它的行动。



更多文件在这里: http://golang.org/pkg/reflect/#Type

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

Here is the container from which I am iterating:

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.

解决方案

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))

}

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

More documentation here: http://golang.org/pkg/reflect/#Type

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

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