Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Go Lang - Reflection

Using Reflection in Go

Reflection in Go allows inspection of types, functions, and variables at runtime. It provides mechanisms to dynamically examine and manipulate code elements, making it useful for tasks like serialization, deserialization, and building generic algorithms.

Key Points:

  • Go's reflect package enables reflection capabilities.
  • Reflection allows querying type information, examining struct fields, and invoking methods dynamically.
  • Use reflection judiciously due to its performance implications and type safety considerations.

Example of Using Reflection in Go

Below is an example demonstrating how to use reflection in Go:


// Example: Using reflection in Go
package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name string
    Age  int
}

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

func inspect(x interface{}) {
    t := reflect.TypeOf(x)
    v := reflect.ValueOf(x)

    fmt.Println("Type:", t)
    fmt.Println("Value:", v)

    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        value := v.Field(i)
        fmt.Printf("Field: %s, Value: %v\n", field.Name, value.Interface())
    }
}
          

Summary

This guide provided an overview of using reflection in Go, including examples of querying type information, examining struct fields, and using reflection for dynamic code inspection. By leveraging reflection, developers can build more flexible and generic algorithms in Go applications.