Search⌘ K
AI Features

Changing Structure Values Using Reflection

Explore how to modify structure field values dynamically in Go using reflection. This lesson covers setting integer and string fields with reflection methods, the benefits of this approach, and important drawbacks such as reduced performance, runtime errors, and maintainability challenges. Gain practical insights into when and how to leverage reflection safely in Go programming.

Learning about the internal structure of a Go structure is handy, but what is more practical is being able to change values in the Go structure, which is the subject of this lesson.

Coding example

Let’s look at the setValues.go code:

Go (1.18.2)
package main
import (
"fmt"
"reflect"
)
type T struct {
F1 int
F2 string
F3 float64
}

In the code above, we define a struct type named T with three fields: F1 of type int, F2 of type string, and F3 of type float64.

Go (1.18.2)
func main() {
A := T{1, "F2", 3.0}
fmt.Println("A:", A)
r := reflect.ValueOf(&A).Elem()
fmt.Println("String value:", r.String())
typeOfA := r.Type()
for i := 0; i < r.NumField(); i++ {
f := r.Field(i)
tOfA := typeOfA.Field(i).Name
fmt.Printf("%d: %s %s = %v\n", i, tOfA, f.Type(), f.Interface())
k := reflect.TypeOf(r.Field(i).Interface()).Kind()
if k == reflect.Int {
r.Field(i).SetInt(-100)
} else if k == reflect.String {
r.Field(i).SetString("Changed!")
}
}
fmt.Println("A:", A)
}

In the code above, A is the variable that is examined in this program. ...