This page combines two related searches: filling structs from a loop (often for ... range over a slice), and golang iterate over struct / golang iterate over struct fields at runtime. It also touches golang forloop basics; typos like foor loop point at the same for statement. For general loop forms, see the for loop in Go guide and structs in Go.
Examples were run with a recent Go toolchain on Linux.
Store slice values into structs with for range
Each string from a slice becomes one row stored in a slice of structs. Named fields in the struct literal keep the intent obvious.
package main
import "fmt"
type Row struct {
Index int
Label string
}
func main() {
names := []string{"AWS", "GoLinux", "Google", "Linux", "Chrome"}
var rows []Row
for i, name := range names {
rows = append(rows, Row{Index: i, Label: name})
}
fmt.Println(rows)
}Run prints five Row values with indices 0 through 4 and the matching labels.
Golang iterate over struct fields with reflect
When you need golang iterate over struct fields generically (for example logging or simple serializers), reflect walks fields by index. This only demonstrates exported fields; unexported fields need different APIs and package boundaries.
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Ada", Age: 36}
v := reflect.ValueOf(p)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
fmt.Println(t.Field(i).Name, v.Field(i).Interface())
}
}Run prints Name Ada then Age 36.
Golang forloop refresher: three-part for
Go has no while; the three-part for covers counted loops.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println(i)
}
}Run prints 0, 1, and 2.
Summary
You can store values in a struct using a for loop by ranging over a source slice and appending structs with explicit fields. Golang iterate over struct at runtime is usually reflect.ValueOf, NumField, and Field(i) when you cannot name fields statically. Golang forloop and misspellings like foor loop still mean Go’s single for keyword with range, three-part, or for { break } shapes.

