Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Reflect Package in GO

4 min readJun 12, 2024

--

Press enter or click to view image in full size

Reflection in Go (Golang) is a powerful feature that allows a program to inspect its own structure and values at runtime. This capability is provided by the reflect package. Reflection is commonly used for tasks like serialization/deserialization, building generic libraries, and testing. Here, I'll provide an overview of how reflection works in Go, along with real-life examples.

Basic Concepts

  1. Type: The kind of value (e.g., int, string, float, struct).
  2. Value: The actual data held by a variable.
  3. Kind: The specific category of a type (e.g., reflect.Int, reflect.Struct).

Key Types and Functions

  1. reflect.TypeOf: Returns the type of the given value.
  2. reflect.ValueOf: Returns the value of the given value.
  3. reflect.Value: A struct type that represents the runtime data.
  4. reflect.Type: A struct type that represents the runtime type information.
  5. reflect.Kind: An enumeration for the kinds of types (e.g., reflect.Int, reflect.Struct).
  6. reflect.Value.Method: Returns a function value corresponding to the method with the given name.

Example 1: Inspecting Types and Values

This example shows how to use reflection to inspect the type and value of a variable.

package main

import (
"fmt"
"reflect"
)

func main() {
var x float64 = 3.4

// Getting the type and value using reflection
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)

fmt.Println("Type:", t)
fmt.Println("Value:", v)
fmt.Printf("Kind is float64: %v\n", v.Kind() == reflect.Float64)
fmt.Printf("Type is float64: %v\n", t == reflect.TypeOf(float64(0)))
}

Output

Press enter or click to view image in full size

Example 2: Modifying Values

Reflection can also be used to modify the values of variables, but this requires the value to be addressable.

Get Muhammad Asghar Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

package main

import (
"fmt"
"reflect"
)

func main() {
var x float64 = 3.4
fmt.Println("Original value:", x)

// Getting the addressable value using reflection
v := reflect.ValueOf(&x).Elem()

// Setting the value
v.SetFloat(7.1)
fmt.Println("Modified value:", x)
}

Output

Press enter or click to view image in full size

Example 3: Struct Tag Parsing

Reflection is often used to parse struct tags in Go. This is useful in tasks like JSON serialization, where struct tags define how fields should be encoded/decoded.

package main

import (
"fmt"
"reflect"
)

type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}

func main() {
p := Person{Name: "Alice", Age: 30}

t := reflect.TypeOf(p)

for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("Field: %s, Tag: %s\n", field.Name, field.Tag.Get("json"))
}
}

Output

Press enter or click to view image in full size

Example 4: Building a Generic Function

Reflection can be used to build generic functions that can work with any type. For instance, let’s create a function that prints the fields and values of any struct.

package main

import (
"fmt"
"reflect"
)

func PrintFields(s interface{}) {
v := reflect.ValueOf(s)

if v.Kind() == reflect.Struct {
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
fmt.Printf("%s: %v\n", field.Name, value)
}
} else {
fmt.Println("Expected a struct")
}
}

type Person struct {
Name string
Age int
}

func main() {
p := Person{Name: "Alice", Age: 30}
PrintFields(p)
}

Output

Press enter or click to view image in full size

Conclusion

Reflection in Go is a powerful tool that allows for runtime type inspection and manipulation. It’s particularly useful for tasks that require generic programming, such as building libraries and frameworks that need to handle different types dynamically. However, reflection should be used judiciously, as it can make code harder to read and maintain, and may introduce performance overhead.

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.