dt3358 2015-01-10 20:39
浏览 128
已采纳

为什么Go panic()采用interface {}而不是…interface {}作为参数?

I noticed panic takes interface{} as an argument, while fmt.Print and the likes take ...interface{}. Wouldn't it be more convenient if panic took ...interface{} as well?

Why did the Go authors define panic as func panic(v interface{}) rather than func panic(v ...interface{}) (like they did with fmt)?

  • 写回答

2条回答 默认 最新

  • doujiang2643 2015-01-10 21:31
    关注

    panic didn't take just one argument at first.
    You can trace back the one argument implementation back to 30th March 2010:
    commit 01eaf78 gc: add panic and recover (still unimplemented in runtime)

    main semantic change is to enforce single argument to panic.

    The spec is fixed in commit 5bb29fb, and commit 00f9f0c illustrates how panic could took before multiple arguments:

    src/pkg/bufio/bufio.go
    
    b, err := NewWriterSize(wr, defaultBufSize)
    if err != nil {
        // cannot happen - defaultBufSize is valid size
        - panic("bufio: NewWriter: ", err.String())
        + panic(err)
    }
    

    That follows a proposal from March 25th, 2010:

    We don't want to encourage the conflation of errors and exceptions that occur in languages such as Java.

    Instead, this proposal uses a slight change to the definition of defer and a couple of runtime functions to provide a clean mechanism for handling truly exceptional conditions.

    During panicking, if a deferred function invocation calls recover, recover returns the value passed to panic and stops the panicking.
    At any other time, or inside functions called by the deferred call, recover returns nil.
    After stopping the panicking, a deferred call can panic with a new argument, or the same one, to continue panicking.
    Alternately, the deferred call might edit the return values for its outer function, perhaps returning an error.

    In those various scenario, dealing with one value to pass around seems easier than dealing with an variable number of arguments (especially when it comes to implement recover in C).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码