赞
踩
通过反射机制,找到相应的Left或者Right广告
- type SearchAdsObj struct {
- Left PositionAdsObj `json:"left"`
- Right PositionAdsObj `json:"right"`
- }
-
- func getFieldByName(obj SearchAdsObj, fieldName string) (interface{}, error) {
- fmt.Printf("getFieldByName: %s \n", fieldName)
- val := reflect.ValueOf(obj)
- // fmt.Printf("getFieldByName val %v \n", val)
-
- if val.Kind() != reflect.Struct {
- fmt.Printf("getFieldByName input is not a struct")
- return nil, fmt.Errorf("getFieldByName input is not a struct")
- }
-
- field := val.FieldByName(fieldName)
- if !field.IsValid() {
- fmt.Printf("getFieldByName field %s not found in the struct", fieldName)
- return nil, fmt.Errorf("getFieldByName field %s not found in the struct", fieldName)
- }
- var inter interface{} = field
- if myStruct, ok := inter.(PositionAdsObj); ok {
- // 如果转换成功,myStruct现在包含MyStruct类型的值
- return myStruct, nil
- } else {
- // 如果转换失败,说明myInterface不包含MyStruct类型的值
- fmt.Println("Conversion failed, myInterface does not contain a PositionAdsObj")
- return nil, fmt.Errorf("Conversion failed, myInterface does not contain a PositionAdsObj")
- }
- }
-
注意 getFieldByName 传入的是SearchAdsObj具体类型的实体,而不能是:obj interface{}
func getFieldByName(obj interface{}, fieldName string) (interface{}, error) {
因为反射访问结构体内部字段时候,需要操作的对象是一个实际类型的结构体
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。