๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Go Reflection Basics

Reflection is a way for a program to read facts about its own values while it runs. The reflect package reports the type and the kind of any value.

Type and kind

TypeOf gives the exact type of a value. Kind gives the family that the type belongs to.

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title string
	Pages int
}

func main() {
	fmt.Println("int:", reflect.TypeOf(42), reflect.TypeOf(42).Kind())
	fmt.Println("string:", reflect.TypeOf("hi"), reflect.TypeOf("hi").Kind())
	fmt.Println("struct:", reflect.TypeOf(Book{}), reflect.TypeOf(Book{}).Kind())
}

Reading values back

ValueOf wraps a value in a handle. Int and String pull the stored value back out.

package main

import (
	"fmt"
	"reflect"
)

func main() {
	fmt.Println(reflect.ValueOf(42).Int())
	fmt.Println(reflect.ValueOf("hello").String())
}

Nil and pointers

A nil interface holds no value and no type. A pointer type has kind ptr and its Elem is the pointed type.

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title string
	Pages int
}

func main() {
	var v any
	fmt.Println(reflect.TypeOf(v) == nil)
	b := Book{Title: "Go", Pages: 120}
	t := reflect.TypeOf(&b)
	fmt.Println(t.Kind())
	fmt.Println(t.Elem())
}

Example

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title string
	Pages int
}

func describe(v any) {
	t := reflect.TypeOf(v)
	fmt.Println(t, t.Kind(), reflect.ValueOf(v))
}

func main() {
	describe(7)
	describe("hi")
	describe(Book{Title: "Go", Pages: 120})
}

Key points

  • reflect.TypeOf returns the type of a value.
  • Kind reports the broad family of a type.
  • reflect.ValueOf returns a handle to the value itself.
  • Int and String read the stored value back from a handle.
  • A nil interface value has no type at all.
  • Elem on a pointer type reaches the type it points to.

In this example, describe takes one value of any type. It prints the type, the kind, and the value for an int. It then does the same for a string and for a struct value.

Note

Reflection reads values at run time, after the program starts.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does the Kind call report for the value 42?