How to find the type of an object in Go?

前端 未结 14 1127
余生分开走
余生分开走 2020-12-12 09:16

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 ?

14条回答
  •  执笔经年
    2020-12-12 09:32

    You can check the type of any variable/instance at runtime either using the "reflect" packages TypeOf function or by using fmt.Printf():

    package main
    
    import (
       "fmt"
       "reflect"
    )
    
    func main() {
        value1 := "Have a Good Day"
        value2 := 50
        value3 := 50.78
    
        fmt.Println(reflect.TypeOf(value1 ))
        fmt.Println(reflect.TypeOf(value2))
        fmt.Println(reflect.TypeOf(value3))
        fmt.Printf("%T",value1)
        fmt.Printf("%T",value2)
        fmt.Printf("%T",value3)
    }
    

提交回复
热议问题