简体   繁体   中英

How to list pointers to all fields of golang struct?

Is there a good way in golang to pass all fields of some struct instance c ?

I'm looking for some syntactic sugar functionality, so that instead of doing this:

method(&c.field1, &c.field2, &c.field3, &c.field4, &c.field5, ...)

I could do this:

method(FieldsPointers(c)...)

I'm rather new to golang and still learning the basics, if there is no good way to do what I want for a good reason, I'd appreciate an explanation as to why.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM