How to find the type of an object in Go?

前端 未结 14 1126
余生分开走
余生分开走 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:18

    You can use: interface{}..(type) as in this 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)
          }
        }
    }
    

提交回复
热议问题