What is the use of reflection in golang?

Go's reflection feature allows us to examine and manipulate the types, values, and structures of objects at runtime. Here's an example of how to use reflection to inspect the fields of a struct:

package main

import (

type Person struct {
    Name string
    Age  int

func main() {
    p := Person{"Alice", 25}

    // Get the type of the person variable using reflection
    t := reflect.TypeOf(p)

    // Loop through the fields of the struct and print their names and types
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        fmt.Printf("Field %d: %s (%s)\n", i+1, field.Name, field.Type)

    // Get the value of the Name field using reflection
    v := reflect.ValueOf(p)
    name := v.FieldByName("Name")
    fmt.Printf("Name: %s\n", name)

In this example, we define a **Person** struct with two fields: **Name** and **Age**. We then create an instance of this struct and use reflection to get its type using **reflect.TypeOf()**. We then loop through the fields of the struct using **t.NumField()** and **t.Field()** to print out their names and types.

We also use reflection to get the value of the **Name** field using **reflect.ValueOf()** and **v.FieldByName()**. We then print out the value of the **Name** field.

Note that reflection can be powerful but also has some performance overhead and can be tricky to use correctly. It's generally recommended to use reflection sparingly and only when necessary.

Related Questions You Might Be Interested