Home >Backend Development >Golang >How to iterate over string fields in a struct using reflection in Go?
Iterating Over String Fields in a Struct
Problem:
Iterating over the string fields of a struct presents a challenge, especially when seeking to perform cleanup or validation operations. Implementing this with a switch-case approach lacks scalability and is unsuitable when leveraging the gorilla/schema for unmarshalling.
Solution:
Reflect provides an avenue for iterating over struct fields and manipulating string fields seamlessly. Here's how it can be achieved:
Example:
<code class="go">package main import ( "fmt" "reflect" "strings" ) type MyStruct struct { A, B, C string I int D string J int } func main() { ms := MyStruct{"Green ", "Eggs", " and ", 2, "Ham ", 15} fmt.Printf("%s%s%s%d%s%d\n", ms.A, ms.B, ms.C, ms.I, ms.D, ms.J) msValuePtr := reflect.ValueOf(&ms) msValue := msValuePtr.Elem() for i := 0; i < msValue.NumField(); i++ { field := msValue.Field(i) if field.Type() != reflect.TypeOf("") { continue } str := field.Interface().(string) str = strings.TrimSpace(str) field.SetString(str) } fmt.Printf("%s%s%s%d%s%d\n", ms.A, ms.B, ms.C, ms.I, ms.D, ms.J) }</code>
Caveats:
The above is the detailed content of How to iterate over string fields in a struct using reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!