Reflection in Golang

Reflection is an advanced programming concept, which in some programming languages allows the program to check types and values at runtime. Go has a package for reflection – the reflect package. In this post, we are going to discuss how to do reflection in Go.

What is Reflection in Programming?

Reflection is the way a programming language can check the type of values at runtime. This is one of the most important properties a programming language has. Go has the reflect package which allows us to do runtime reflection in Go.

Importing reflect package in Golang

To do reflection in Go, we need to import the reflect package.

import "reflect"

The “reflect” package

The reflect package is the one that contains all the functions we can use for reflection. Here we will explore some of it.

1. Get the type runtime

We can get the type of value runtime using reflect.TypeOf.

package main

import (
	"fmt"
	"reflect"
)

type Person struct{
	Name string
	Age int
}

func main() {
	p := Person{"Mike", 22}
	
	fmt.Println(reflect.TypeOf(p))      // main.Person
}

2. Getting the value at Runtime

package main

import (
	"fmt"
	"reflect"
)

type Person struct{
	Name string
	Age int
}

func main() {
	p := Person{"Mike", 22}
        fmt.Println(reflect.ValueOf(p))     // {Mike 22}
}

3. Getting the number of fields in a struct

NumField returns the number of fields a struct has.

package main

import (
	"fmt"
	"reflect"
)

type Person struct{
	Name string
	Age int
}

func main() {
	p := Person{"Mike", 22}
        fmt.Println(reflect.ValueOf(p).NumField())      // 2
}

4. Getting the number of methods

The NumMethod returns the number of methods the struct contains and can be used just like before.

5. IsValid() Method

To check whether it is a value or not the isValid method can be used.

package main

import (
	"fmt"
	"reflect"
)

type Person struct{
	Name string
	Age int
}

func main() {
	p := Person{"Mike", 22}
        fmt.Println(reflect.ValueOf(p).IsValid())      // true
}

6. reflect Kind() Method

The kind of value can also be extracted using the kind function as shown below.

package main

import (
	"fmt"
	"reflect"
)

type Person struct{
	Name string
	Age int
}

func main() {
	p := Person{"Mike", 22}
        fmt.Println(reflect.TypeOf(p).Kind())          // struct
}

The use of reflection

Reflection is used when we want to extract important information about value like the type or kind. It improves the way we handle functions and their uses and can help make them more generic and reduce code.