duanhui1185 2016-05-17 08:20
浏览 43
已采纳

是否可以使用golang中的自定义库触发编译时错误?

Let's say, I have min() (just for example) a variadic function to define the smallest value from multiple values provided.

If the caller don't provided any parameter, I want to halt compile process (as this would be the bug in the caller, not error in my function).

How to do that?

  • 写回答

1条回答 默认 最新

  • duanjieyi6582 2016-05-17 08:40
    关注

    Calling a function which has variadic parameter and passing no arguments is valid by the language spec. So you can't make it a compile-time error.

    However, you may modify the signature of your function to have a non-variadic and a variadic parameter, and then calling it with no arguments would indeed be a compile-time error:

    func min(first int, rest ...int) int {
        m := first
        for _, v := range rest {
            if v < m {
                m = v
            }
        }
        return m
    }
    

    This will force callers to pass at least 1 argument, else it will be a compile-time error. This min() function can be called like this:

    min(1)
    min(1, 2)
    min(1, 2, -3)
    

    But attempting to call it without any arguments results in compile-time error:

    min() // Error: not enough arguments in call to min
    

    If you want the callers to pass at least 2 arguments:

    func min(first, second int, rest ...int) int {
        return 0 // Implement your logic here
    }
    

    Note:

    The above example is also more efficient if the caller just wants to pass 1 argument, as variadic parameters are implemented with slices in the background, and if the caller passes only 1 argument, no slice will have to be created, a nil slice will be passed (this can be verified by printing rest == nil – which will be true).

    The potential downside is that if you have a slice, you can't just pass it to the function, but you may do the following:

    s := []int{1, 2, -3}
    fmt.Println(min(s[0], s[1:]...))
    

    Which is passing the first element, and slicing the slice to pass the rest and using ... to pass it as the value for the variadic parameter. Don't forget to check if the slice has at least 1 element, else the above code panics at runtime.

    Try the examples on the Go Playground.

    If you can't or don't want to modify the signature of your function, your only option is to panic or exit from the app at runtime, but no possibility to fail at compile-time.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么