I have a struct with 8 fields of bool, and an array with 8 boolean values.
How can I assign each array value to corresponding field in struct?
I knew I can use s.f = a[n]
, but what if there are more fields?
You may use the reflect package to set exported fields:
var y = []bool{true, false, true}
var x struct{ X, Y, Z bool }
v := reflect.ValueOf(&x).Elem()
for i := 0; i < v.NumField(); i++ {
v.Field(i).SetBool(y[i])
}
fmt.Println(x) // prints {true, false, true}