Types in Go
Check variable type
The type of a variable in Go can be retrieved by formatting the output:
var stringVar string
fmt.Printf("Type: %T\n", stringVar)
The example above outputs: Type: string
.
Another way of obtaining the variable type is to use reflect.TypeOf
.
var stringVar string
fmt.Printf("reflect.TypeOf(): %s\n", reflect.TypeOf(stringVar))
The example above outputs: reflect.TypeOf(): string
.
reflect
package can be also used to get the kind of type of a variable. For exmaple, whether a variable is a struct, a slice, a map, or a pointer.
type SomeCustomType struct{}
var someCustomType SomeCustomType
fmt.Printf("reflect.TypeOf().Kind(): %s\n", reflect.TypeOf(someCustomType).Kind())
The example above outputs: reflect.TypeOf().Kind(): struct
.
Some more examples for other types:
import (
"fmt"
"reflect"
)
type SomeCustomType struct{}
var (
stringVar string
someCustomType SomeCustomType
sliceOfSomeCustomType []SomeCustomType
mapStringSomeCustomType map[string]SomeCustomType
pointerToSomeCustomType *SomeCustomType
)
func printType(v any) {
fmt.Printf("Type: %T\n", v)
fmt.Printf("reflect.TypeOf(): %s\n", reflect.TypeOf(v))
fmt.Printf("reflect.TypeOf().Kind(): %s\n\n", reflect.TypeOf(v).Kind())
}
func main() {
printType(stringVar)
printType(someCustomType)
printType(sliceOfSomeCustomType)
printType(mapStringSomeCustomType)
printType(pointerToSomeCustomType)
}
The example above outputs:
Type: string
reflect.TypeOf(): string
reflect.TypeOf().Kind(): string
Type: main.SomeCustomType
reflect.TypeOf(): main.SomeCustomType
reflect.TypeOf().Kind(): struct
Type: []main.SomeCustomType
reflect.TypeOf(): []main.SomeCustomType
reflect.TypeOf().Kind(): slice
Type: map[string]main.SomeCustomType
reflect.TypeOf(): map[string]main.SomeCustomType
reflect.TypeOf().Kind(): map
Type: *main.SomeCustomType
reflect.TypeOf(): *main.SomeCustomType
reflect.TypeOf().Kind(): ptr