douhandie6615 2014-10-11 06:46
浏览 22
已采纳

在Go中使用反射检查兼容类型

Although I am aware that it might not be idiomatic to panic in Go, I would like to test to ensure a function panics under certain conditions and not in others.

An example of the function.

func PanicOnErr(potentialErr error) {
    if potentialErr != nil {
        panic(potentialErr)
    }
}

The following is an implementation for checking if the function will panic.

func InvocationCausedPanic(f interface{}, params ...interface{}) bool {
    // Obtain the function's signature.
    reflectedFunc := reflect.ValueOf(f)
    funcType := reflect.TypeOf(f)

    if funcType.NumIn() != len(params) {
        panic("InvocationCausedPanic called with a function and an incorrect number of parameter(s).")
    }

    reflectedParams := make([]reflect.Value, len(params))
    for paramIndex, paramValue := range params {
        expectedType := funcType.In(paramIndex)
        actualType := reflect.TypeOf(paramValue)

        if actualType != expectedType {
            errStr := fmt.Sprintf("InvocationCausedPanic called with a mismatched parameter type [parameter #%v: expected %v; got %v].", paramIndex, expectedType, actualType)
            panic(errStr)
        }

        reflectedParams[paramIndex] = reflect.ValueOf(paramValue)
    }

    return invoke(reflectedFunc, reflectedParams)
}

func invoke(reflectedFunc reflect.Value, reflectedParams []reflect.Value) (panicked bool) {
    defer func() {
        if r := recover(); r != nil {
            panicked = true
        }
    }()

    reflectedFunc.Call(reflectedParams)
    return
}

Calling either of the following will cause the type-check to fail.

InvocationCausedPanic(PanicOnErr, errors.New("Some error."))
InvocationCausedPanic(PanicOnErr, nil)

However, it seems possible to call PanicOnErr using both nil and something generate by calling errors.New (seems to be of type *errors.errorString).

As such, is there a way to check if the type of some parameter is suitable for invoking some function?

While I know it is possible to use defer and recover to more simply test the function, I am curious as to whether it is possible to write a general function that can accept any function and parameters and determine whether it resulted in a panic (assuming the function completes).

Relevant Go Playground: http://play.golang.org/p/qUG7OGuIbD

  • 写回答

1条回答 默认 最新

  • dongyan3237 2014-10-11 13:13
    关注

    Use this function to determine if the parameter is compatible:

    func compatible(actual, expected reflect.Type) bool {
      if actual == nil {
        k := expected.Kind()
        return k == reflect.Chan || 
               k == reflect.Func || 
               k == reflect.Interface || 
               k == reflect.Map || 
               k == reflect.Ptr || 
               k == reflect.Slice
      }
      return actual.AssignableTo(expected)
    }
    

    <kbd>playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集