dongwenxiu5200 2017-05-03 22:54
浏览 126
已采纳

如何将保存错误对象的reflect.Value分配给类型为error的普通变量?

I am trying to write a function that returns back to its caller an error result taken from the result slice of reflect.ValueOf(somefunc).Call(someargs).

I've tried numerous variants of refer. calls, and type assertions. but cannot seem to get the compiler to let me put the actual concrete value from the reflect.Value slice back into an ordinary error variable.

Here's the code, using os.Getwd as the function:

   var somefunc interface{}
   var errToCaller *error
   somefunc = os.Getwd
   ftype := reflect.TypeOf(somefunc)
   errType := reflect.TypeOf(errToCaller).Elem()
   resType := ftype.Out(1)
   fmt.Println("resType.Implements(errType) = ",
      resType.Implements(errType))
   res := reflect.ValueOf(somefunc).Call([]reflect.Value{})
   fmt.Printf("res[1] as %%v = %v
", res[1])
   fmt.Printf("res[1] as %%#v = %#v
", res[1])
   fmt.Printf("ValueOf(res[1]) as %%v = %v
",
      reflect.ValueOf(res[1]))
   fmt.Printf("ValueOf(res[1]) as %%#v = %#v
",
      reflect.ValueOf(res[1]))
   fmt.Printf("ValueOf(res[1]).Type() as %%#v = %#v
",
      reflect.ValueOf(res[1]).Type())
   fmt.Printf("ValueOf(res[1]).Interface() as %%#v = %#v
",
      reflect.ValueOf(res[1]).Interface())
   // *errToCaller = reflect.ValueOf(res[1])
   // *errToCaller = reflect.ValueOf(res[1]).Interface()
   // *errToCaller = reflect.ValueOf(res[1]).Interface().(error)

With the following output:

resType.Implements(errType) =  true
res[1] as %v = <nil>
res[1] as %#v = error(nil)
ValueOf(res[1]) as %v = <error Value>
ValueOf(res[1]) as %#v = reflect.Value{typ:(*reflect.rtype)(0x4b9a60), ptr:(unsafe.Pointer)(0xc42000a3f0), flag:0x94}
ValueOf(res[1]).Type() as %#v = &reflect.rtype{size:0x18, ptrdata:0x10, hash:0x500c1abc, tflag:0x7, align:0x8, fieldAlign:0x8, kind:0x19, alg:(*reflect.typeAlg)(0x4a62d0), gcdata:(*uint8)(0x4daa41), str:21371, ptrToThis:184032}
ValueOf(res[1]).Interface() as %#v = error(nil)

I've abbreviated the example to remove lots of other Printf statements that indicate (to me at least) that the types are the same (even in what I think are the relevant fields of the reflect.Value struct). Why, when all of the various print statements seem to be telling me the result is an error value, can't I assign it to my local variable?

Uncommenting the first assignment in the code example above results in this complaint from the compiler:

./passerror.go:30: cannot use reflect.ValueOf(res[1]) (type reflect.Value) as type error in assignment:
        reflect.Value does not implement error (missing Error method)

So I figured I needed the Interface() result, but still no luck (using the 2nd assignment commented out above):

./passerror.go:31: cannot use reflect.ValueOf(res[1]).Interface() (type interface {}) as type error in assignment:
        interface {} does not implement error (missing Error method)

Finally, a type assertion on the Interface() return value causes a panic:

panic: interface conversion: reflect.Value is not error: missing method Error

No matter what I've tried, I can't seem to escape from the dreaded reflect.Value which prevents me from doing the assignment to ordinary error variable. I have tried Set() also without success, but perhaps incorrectly.

I would be forever grateful for insight and/or the magic incantation to do this.

EDIT Thanks https://stackoverflow.com/users/965900/mkopriva for the spot on comment. The code requires a real error variable, not just a *error, after which localerr = res[n].Interface().(error) worked perfectly. (also changed function to os.Chdir using a bogus argument to trigger a non-nil error value)

  • 写回答

1条回答 默认 最新

  • douyao3895 2017-05-04 13:48
    关注

    The value returned from Call is a slice of reflect.Values, so there is no need to wrap the result in another reflect.ValueOf call like you do in your example code:

    reflect.ValueOf(res[1]) // not what you want
    

    Doing that will change the value's underlying type from error to reflect.Value which is the reason why subsequently calling .Interface().(error) causes the program to panic.

    So to fix your code just call .Interface().(error) directly on the result like so:

    res[1].Interface().(error)
    

    And, as already pointed out by Cerise Limón, when you do type assertion it's good practice to use the "comma ok" idiom to avoid unnecessary panics.

    err, ok := res[1].Interface().(error)
    if !ok {
         // oops
    }
    

    Or, a bit more concise alternative:

    if err, ok := res[1].Interface().(error); ok && err != nil {
         // it's a non-nil error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺