golang通过反射获取结构体的字段

func main() {
	fmt.Println(GetFieldName(Student{}))
	fmt.Println(GetFieldName(&Student{}))
	fmt.Println(GetFieldName(""))

	fmt.Println(GetTagName(&Student{}))
}


type Student struct {
	Name   string  `json:"name"`
	Age       int			`json:"age"`
	Grade   int        `json:"grade"`
}



//获取结构体中字段的名称
func GetFieldName(structName interface{}) []string  {
	t := reflect.TypeOf(structName)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	if t.Kind() != reflect.Struct {
		log.Println("Check type error not Struct")
		return nil
	}
	fieldNum := t.NumField()
	result := make([]string,0,fieldNum)
	for i:= 0;i 1 {
			tagName = tags[1]
		}
		result = append(result,tagName)
	}
	return result
}


注:可能会出现的问题

structNametype不是结构体类型  就会报以下错误:panic: reflect: NumField of non-struct type
故需要在程序中加以判断

你可能感兴趣的:(go小程序)