简体   繁体   English

如何列出指向golang结构所有字段的指针?

[英]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 ? golang 中是否有传递某个 struct 实例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.我对 golang 还是比较陌生,并且仍在学习基础知识,如果没有好的方法可以做我想做的事情有充分的理由,我希望能解释一下原因。

Besides all sql specified tools, if you want to access to pointers of a struct, you can use reflect .除了所有 sql 指定的工具,如果你想访问一个结构体的指针,你可以使用reflect Be warned that the package is tricky and rob pike said it is not for everyone.请注意,包裹很棘手,rob pike 说它并不适合所有人。

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. reflect.Value有方法NumField返回结构中的字段数和Field(int) ,它接受字段的索引并返回字段本身。

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.首先,您需要将结构的指针传递给Scan ,因为您正在修改数据并且该值必须是可设置的。 That is why we are calling .Elem() , to dereference the pointer.这就是为什么我们调用.Elem()来取消对指针的引用。

Second, reflect.Value.Set must use a same type to set.其次, reflect.Value.Set必须使用相同的类型来设置。 You cannot set uint32 to a int64 like normal assignment.您不能像正常赋值那样将uint32设置为int64

Playground: https://play.golang.org/p/grvXAc1Px8g游乐场: https : //play.golang.org/p/grvXAc1Px8g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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