将golang中变量重置为零的reflect方法

下面给出简单的代码,这里通过将变量重置为零来实现过滤字段的目的:

type student struct {
	Age    int    `json:"age,omitempty"`
	Name   string `json:"name,omitempty"`
	School string `json:"school,omitempty"`
}

var st = student{
	Age:    10,
	Name:   "john smith",
	School: "a high school",
}

var dic = map[string]int{
	"age":    0,
	"name":   1,
	"school": 2,
}

var filters = []string{
	"name",
	"school",
}

func initStudentElems(st *student, fields []string) bool {
	v := reflect.Indirect(reflect.ValueOf(st))
	for _, field := range fields {
		idx, exist := dic[field]
		if !exist {
			return false
		}
		vf := v.Field(idx)
		vf.Set(reflect.Zero(vf.Type()))
	}
	return true
}

func printMarshalIdent(st *student) error {
	b, err := json.MarshalIndent(st, "", "    ")
	if err != nil {
		return err
	}

	fmt.Println(string(b))
	return nil
}

func main() {
	printMarshalIdent(&st)
	initStudentElems(&st, filters)
	printMarshalIdent(&st)
}

 如果不希望使用二次映射,可以考虑使用reflect库中,Value结构体的FieldByName成员函数。

原文地址:https://www.cnblogs.com/albizzia/p/10341404.html