Go Tricks - unpack slice to struct fields
Use reflect
, in this example, we only show to unpack an int slice to a struct whose fields are all int type.
package main
import (
"errors"
"fmt"
"reflect"
)
type Location struct {
X int
Y int
Z int
}
func (loc Location) String() string {
return fmt.Sprintf("X: %d, Y: %d, Z: %d", loc.X, loc.Y, loc.Z)
}
func unpackIntSliceToStruct(slice []int, st interface{}) error {
s := reflect.ValueOf(st).Elem()
if s.Kind() != reflect.Struct {
return errors.New("st must be a struct pointer")
}
l := s.NumField()
if len(slice) != l {
return errors.New("number of fields doesn't match")
}
for i := 0; i < l; i++ {
f := s.FieldByIndex([]int{i})
if f.CanAddr() {
f.SetInt(int64(slice[i]))
}
}
return nil
}
func main() {
points := []int{1, 2, 3}
loc := Location{}
err := unpackIntSliceToStruct(points, &loc)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(loc)
}
Result:
X: 1, Y: 2, Z: 3