猿问

我可以得到一个字段是否已经在 golang 中分配了反射

我有一个结构如下:

type Demo struct{
     A string
     B string}

我有一个实例如下:

demo := Demo{A:"a"}

A的字段已显式分配值,但字段B未分配值。现在,我想知道是否存在一些方法可以通过反射获取实例A的字段?

在这里,我想获得字段A


红糖糍粑
浏览 97回答 1
1回答

叮当猫咪

无法确定某个字段是否显式分配了一个值,但可以确定是否存在不等于该字段零值的字段。遍历字段。如果字段的值不等于字段类型的零值,则返回 true。func hasNonZeroField(s interface{}) bool {&nbsp; &nbsp; v := reflect.ValueOf(s)&nbsp; &nbsp; if v.Kind() == reflect.Ptr {&nbsp; &nbsp; &nbsp; &nbsp; v = v.Elem()&nbsp; &nbsp; }&nbsp; &nbsp; t := v.Type()&nbsp; &nbsp; for i := 0; i < t.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; sf := t.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; fv := v.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; switch sf.Type.Kind() {&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if !fv.IsNil() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Struct:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if hasNonZeroField(fv.Interface()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // case reflect.Array:&nbsp; &nbsp; &nbsp; &nbsp; // TODO: call recursively for array elements&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if reflect.Zero(sf.Type).Interface() != fv.Interface() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false}在操场上运行它。
随时随地看视频慕课网APP

相关分类

Go
我要回答