dongyo1959 2014-10-12 02:01
浏览 316
已采纳

使用反射调用带有nil参数的函数会导致“使用零值参数调用”的紧急情况

I'm trying to test a function that accepts a parameter of the type "error". The function should panic under certain situations and I'm trying to test scenarios.

However, when I try to use reflect.Call on a nil value (which can be passed into a function that accepts something of type "error"), it seems to result in a panic with the following message:

reflect: Call using zero Value argument

I have found the following posts but I am failing to integrate it into my function.

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

In the playground above, I would like the call to InvocationCausedPanic(PanicOnErr, nil) to return false, however, the above panic from reflect is causing a false positive.

Are there any modifications I can make to the InvocationCausedPanic or the invoke functions to make this work (while retaining its ability to test other functions that cannot accept nil as an argument - a function that accepts a string for instance)?

Perhaps the issue is in how the function is called?

I've tred things like InvocationCausedPanic(PanicOnErr, new(error)) or InvocationCausedPanic(PanicOnErr, error(nil)) to no avail.

Thanks for any advice.

  • 写回答

1条回答 默认 最新

  • douguangxiang0363 2014-10-12 02:28
    关注

    If the parameter value is nil, then use a zero value of the function parameter type.

        if paramValue == nil {
            reflectedParams[paramIndex] = reflect.New(expectedType).Elem()
        } else {
            reflectedParams[paramIndex] = reflect.ValueOf(paramValue)
        }
    

    <kbd>playground</kbd>

    You can simplify the code if you compute the reflect value and then check assignability. With this change, the compatible function is not required.

    for paramIndex, paramValue := range params {
        if paramValue == nil {
            reflectedParams[paramIndex] = reflect.New(expectedType).Elem()
        } else {
            reflectedParams[paramIndex] = reflect.ValueOf(paramValue)
        }
        expectedType := funcType.In(paramIndex)
        actualType := reflectedParams[paramIndex].Type()
        if !actualType.AssignableTo(expectedType) {
            errStr := fmt.Sprintf("InvocationCausedPanic called with a mismatched parameter type [parameter #%v: expected %v; got %v].", paramIndex, expectedType,actualType)
            panic(errStr)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办