type Stu struct { Id *int Id1 *int32 Id2 *int64 B *bool } func (this *TestBeanSuite) Test010_IniStru() { var stu = &Stu{} baseutils.InitStruNilPtrField(stu) golog.Info(stu) } 2024-10-11 16:49:16.190 [INFO] {"Id":0,"Id1":0,"Id2":0,"B":false}
func InitStruNilPtrFields(Stru any) { var fields = FindStructNilPtrFields(Stru) for _, field := range fields { switch field.Type.Elem().Kind() { case reflect.Int: xreflect.SetField(Stru, field.Name, new(int)) case reflect.Int32: xreflect.SetField(Stru, field.Name, new(int32)) case reflect.Int64: xreflect.SetField(Stru, field.Name, new(int64)) case reflect.String: xreflect.SetField(Stru, field.Name, new(string)) case reflect.Bool: xreflect.SetField(Stru, field.Name, new(bool)) } } } func FindStructNilPtrFields(Stru any) []reflect.StructField { var fields = make([]reflect.StructField, 0) if Stru == nil { return fields } if !IfTypeStru(reflect.TypeOf(Stru)) { return fields } value := reflect.ValueOf(Stru) if value.Kind() == reflect.Ptr { value = value.Elem() } var struType = reflect.TypeOf(Stru) if struType.Kind() == reflect.Ptr { struType = struType.Elem() } for i := 0; i < struType.NumField(); i++ { var field = struType.Field(i) if field.Type.Kind() == reflect.Ptr && value.FieldByName(field.Name).IsNil() { fields = append(fields, field) } } return fields }
标签:初始化,struType,Name,fields,Stru,reflect,field,go,指针 From: https://blog.csdn.net/leijmdas/article/details/142858485