There is the typeof
in C; there is typeof
in JavaScript; and there is type()
in Python to see what type has an object.
In Go, there is not typeof
, nor type
in the basic syntax, but there are three ways to get an object's type:
The simplest way.
n := 3.14
fmt.Printf("%T", n)
// float64
We have to prepare it a little bit:
- Use .(type) inside type switch.
- Type switch can be done on an interface value only.
var n interface{}
n = 3.14
switch n.(type) {
case int:
fmt.Println("int")
case float32:
fmt.Println("float32")
case float64:
fmt.Println("float64")
default:
fmt.Println("unknown")
}
// float64
An import is needed from the standard library. Here is that we missed in the basic syntax. :)
import "reflect" // outside in the import section
n := 3.14
fmt.Println(reflect.TypeOf(n).String())
// float64