Master Go Reflection: Read and Modify Struct Fields at Runtime
This article explains Go's powerful reflection feature, walks through importing the reflect package, outlines the step‑by‑step process to obtain Type and Value objects, and provides complete code examples that read, modify, and display struct fields while noting performance considerations.
What Is Reflection?
Reflection allows a Go program to inspect and modify its own structure at runtime. The reflect package provides the API, with the two most common types being reflect.Type (describing a value's type) and reflect.Value (holding the actual value).
Basic Usage
To use reflection, import the reflect package and follow these steps:
Obtain a reflection object ( reflect.Type and reflect.Value) from an interface value.
Query the object for type or value information.
Modify the value if needed.
Example: Reading and Setting Struct Fields
Define a Struct
type Person struct {
Name string
Age int
}Read Fields with Reflection
package main
import (
"fmt"
"reflect"
)
func printFields(person interface{}) {
val := reflect.ValueOf(person)
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
value := val.Field(i)
fmt.Printf("%s: %v
", field.Name, value.Interface())
}
}Set a Field with Reflection
func setAge(person interface{}, newAge int) {
val := reflect.ValueOf(person).Elem()
ageField := val.FieldByName("Age")
if ageField.IsValid() && ageField.CanSet() {
ageField.SetInt(int64(newAge))
}
}Complete Program with Main Function
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func printFields(person interface{}) {
val := reflect.ValueOf(person)
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
value := val.Field(i)
fmt.Printf("%s: %v
", field.Name, value.Interface())
}
}
func setAge(person interface{}, newAge int) {
val := reflect.ValueOf(person).Elem()
ageField := val.FieldByName("Age")
if ageField.IsValid() && ageField.CanSet() {
ageField.SetInt(int64(newAge))
}
}
func main() {
p := Person{Name: "John Doe", Age: 30}
fmt.Println("Before setting age:")
printFields(p)
setAge(&p, 31) // note: pass pointer to allow modification
fmt.Println("After setting age:")
printFields(p)
}The program first prints the original fields, then uses setAge to change Age from 30 to 31, and prints the fields again to show the update.
Limitations of Reflection
While reflection is powerful, it incurs performance overhead and is slower than direct code. Use it judiciously, only when static approaches are impractical.
Conclusion
Reflection offers a robust mechanism for runtime inspection and modification of Go programs. By mastering the reflect package, developers can write more flexible and dynamic code, though they should remain aware of its cost.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
