How to use Reflection in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Reflection in Golang is about getting to know the data types of the data that we are dealing with at runtime. There are often certain scenarios where we would want to know the data type of a certain variable that we are getting at runtime or something similar.

With the help of reflection, we can extract the type, values and kind of any data type in Golang.

In this article, we will explore different third-party functions that are used in reflection.

Example 1 – reflect.TypeOf()

It is used to return the value of type reflect. In simple words, it is used to know what is the data type.

Consider the code shown below where we will make use of this function.

package main

import (
   "fmt"
   "reflect"
)

func main() {
   var name string = "TutorialsPoint"

   fmt.Println(reflect.TypeOf(name))

   sl := []int{1, 2, 3, 4, 5}

   fmt.Println(reflect.TypeOf(sl))

   num := 989

   fmt.Println(reflect.TypeOf(num))
}

Output

If we run the command go run main.go on the above command, we will get the following output in the terminal.

string
[]int
int

Example 2 – reflect.ValueOf()

It is used when we want to find the value of the variable. Consider the code shown below where we will make use of this function.

package main

import (
   "fmt"
   "reflect"
)

func main() {
   var name string = "TutorialsPoint"

   fmt.Println(reflect.ValueOf(name))

   sl := []int{1, 2, 3, 4, 5}

   fmt.Println(reflect.ValueOf(sl))

   num := 989

   fmt.Println(reflect.ValueOf(num))
}

Output

If we run the command go run main.go on the above command, we will get the following output in the terminal.

TutorialsPoint
[1 2 3 4 5]
989

Example 3

We can also find the number of fields inside a struct. Consider the code shown below.

package main

import (
   "fmt"
   "reflect"
)

type Person struct {
   age          int
   name          string
   number       float64
   isMarries    bool
}

func main() {
   p := Person{10, "ABCD", 15.20, true}
   typeT := reflect.TypeOf(p)
   fmt.Println(typeT.NumField())
}

Output

If we run the command go run main.go on the above command, we will get the following output in the terminal.

4
raja
Updated on 01-Nov-2021 07:24:26

Advertisements