Avatar ·

How to iterate over all fields of a struct in Go? (iteration over struct fields)

Hello everyone! I just started learning Go and encountered a problem: I have a struct with several fields, and I need to programmatically iterate over all its fields, for example, to print their values or serialize them into a map. Here's an example of my struct: ```go type User struct { Name string Age int Email string } ``` I want to write a function that takes `User` and prints all fields in `key: value` format. I tried using a regular loop, but Go does not allow iterating over struct fields like an array or map. ```go func PrintFields(u User) { for _, field := range u { // Error: cannot range over u (type User) fmt.Println(field) } } ``` I understand that in other languages (e.g., Python or JavaScript) this is done easily