Besides all sql specified tools, if you want to access to pointers of a struct, you can use reflect
. Be warned that the package is tricky and rob pike said it is not for everyone.
reflect.Value
has methods NumField
which returns the numbber of fields in the struct and Field(int)
which accepts the index of a field and return the field itself.
But as you want to set a value to it, it is more complicated than just calling the two methods. Let me show you in code:
func Scan(x interface{}) {
v := reflect.ValueOf(x).Elem()
for i := 0; i < v.NumField(); i++ {
switch f := v.Field(i); f.Kind() {
case reflect.Int:
nv := 37
f.Set(reflect.ValueOf(nv))
case reflect.Bool:
nv := true
f.Set(reflect.ValueOf(nv))
}
}
}
First, you need to pass a pointer of the struct into Scan
, since you are modifying data and the value must be settable. That is why we are calling .Elem()
, to dereference the pointer.
Second, reflect.Value.Set
must use a same type to set. You cannot set uint32
to a int64
like normal assignment.
Playground: https://play.golang.org/p/grvXAc1Px8g