CodeBlanks Logo Icon CodeBlanks

reflect.Type

Learn to get type info with Type.

reflect.Type

reflect.TypeOf(v) returns a reflect.Type. Name() gives the type's name and Kind() its underlying kind.

type Kullanici struct{ Ad string }
t := reflect.TypeOf(Kullanici{})
fmt.Println(t.Name(), t.Kind())  // Kullanici struct

The name is the one you chose; the kind comes from a fixed list such as struct, int, slice, map.

Branching on Kind

A generic function can behave differently depending on the kind of the incoming value:

switch reflect.TypeOf(v).Kind() {
case reflect.Int:
    fmt.Println("tamsayı")
case reflect.Slice:
    fmt.Println("dilim")
}

Kind constants are defined in the package with names like reflect.Int, reflect.String, reflect.Struct.

Practice Name and kind

Define type Urun struct{ Fiyat int }. In main, get t := reflect.TypeOf(Urun{}) and print t.Name() and t.Kind() with one fmt.Println.

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

type Urun struct{ Fiyat int }

func main() {
    t := reflect.TypeOf(Urun{})
    fmt.Println(t.Name(), t.Kind())
}

Expected output

Urun struct

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>type Yas int</code>, what does <code>reflect.TypeOf(Yas(5)).Kind()</code> return?

  • int Correct answer
  • Yas
  • struct
  • main.Yas

Explanation: Kind gives the underlying kind; Yas is a defined type but its base is int. Name() would return "Yas".

2 Get the kind

Question
t := reflect.TypeOf([]int{1, 2})
fmt.Println(t.____())  // slice
Answer
t := reflect.TypeOf([]int{1, 2})
fmt.Println(t.Kind())  // slice

Explanation: Kind() returns the underlying kind; for []int it is slice.

3 Value and its kind

Term Meaning
42 int
"Go" string
[]int{1} slice
map[string]int{} map

All lessons in Advanced