duanhuokuang5280 2017-11-25 18:14 采纳率: 100%
浏览 34
已采纳

将界面转换为另一个并复制内容

I've got the following method:

func ValidateParam(conf map[string]interface{}, paramName string, out interface{}) error {
    param, ok := conf[paramName]

    if !ok {
        return errors.New("some error")
    }

    // ...
}

I would like to be able to call it like so:

myVar := "some text"
err := ValidateParam(conf, "my_var_param", &myVar)

myOtherVar := &MyStruct{}
err := ValidateParam(conf, "my_struct_param", myOtherVar)

The idea is:

  • Get the param using the conf map
  • Check that this param could be converted into the same type as out
  • Hydrate out using the param

=> It is kind of the same process as for json.Unmarshal(data, &myVar) or when doing a query with mgo query.Collection("col").One(&myVar)

I can't find how to achieve this, any help would be more than welcome.

Cheers

  • 写回答

1条回答 默认 最新

  • doulaozhi6835 2017-11-25 18:28
    关注

    One option is to use the reflect package:

    The basic idea is to create reflect.Values for input and output, check if input is assignable to output and then assign.

    func ValidateParam(conf map[string]interface{}, paramName string, out interface{}) error {
        param, ok := conf[paramName]
    
        if !ok {
            return errors.New("some error")
        }
    
        // Output is pointer to value.
        vo := reflect.ValueOf(out)
        if vo.Kind() != reflect.Ptr {
            return errors.New("out must be poitner")
        }
        vo = vo.Elem()  // deref ptr
    
        // Can input be assigned to output?
        vi := reflect.ValueOf(param)
        if !vi.Type().AssignableTo(vo.Type()) {
            return fmt.Errorf("param %s of type %v is not assignable to %v", paramName, vi.Type(), vo.Type())
        }
    
        vo.Set(vi)
        return nil
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?