zoukankan      html  css  js  c++  java
  • 将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成员函数。

  • 相关阅读:
    CSS hack:针对IE6,IE7,firefox显示不同效果
    让IE6支持png24透明/半透明的方法
    IE8的css hack
    jQuery Mobile笔记三
    jQuery Mobile笔记二
    js常见面试题
    CSS3-transform3D
    CSS3-transform-style
    CSS3-媒体类型
    CSS3-盒模型-resize属性
  • 原文地址:https://www.cnblogs.com/albizzia/p/10341404.html
Copyright © 2011-2022 走看看