douju6651 2012-09-15 04:42
浏览 24
已采纳

内置Go中“必备”模式的帮助器

Is there a more built-in wrapper to make a function that returns (X, error) successfully execute or abort, like regexp.MustCompile?

I'm talking about something like this, but more "built-in".

  • 写回答

3条回答 默认 最新

  • dowjgrm6787 2012-09-16 23:36
    关注

    There is not. The best you'll get is something like this:

    func Must(fn func() (interface{}, error)) interface{} {
        v, err := fn()
        if err != nil {
            log.Fatalln(err)
        }
        return v
    }
    

    Then to use it:

    Must(func() (interface{}, error) {
        return template.ParseGlob(pattern)
    }).(*template.Template)
    

    Assuming that template.ParseGlob(pattern) is the call you wanted to wrap.

    Go does not have parametric polymorphism, so this kind of code will end up requiring type assertions to restore the original type and so (in my opinion) is more effort than it's worth. The tidiest, idiomatic error handling you'll get for long chains of potential failure is simply to check for an error, and return it. Defer your cleanup handlers:

    func MyFunc() (err error) {
        a, err := blah1()
        if err != nil {
            return
        }
        defer a.Close()
        b, err := blah2(a)
        if err != nil {
            return
        }
        defer b.Close()
        // ad nauseam
    }
    

    Long and tedious, but at least it's explicit and easy to follow. Here are two modules I wrote that are crying out for parametric polymorphism that might give you some ideas for dealing without it:

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度