dongtan4046 2018-08-08 13:35
浏览 37
已采纳

我可以通过GO中的方法扩展错误接口吗?

I've worked with C# for years so I'm trying to find similarities in GO (I'm quite new to this).

My goal:
I would like to extend the interface error by a method like Check() so I'm able to call error.Check() just because of a (in my opinion) better readable code.

My current state:
I've already learned how to extend types by methods with this syntax:

func (foo T) MyExtension() returnType {
    // return something
}

My problem:
It looks like this only applies to types but not interfaces. As I've seen so far error is an interface that's used by many packages to describe a base of their own error-types. I dont want to extend this error-types (from packages) but rather want to extend the interface to cover them all. I couldn't find any syntax for that. As I also don't know the technical term for this (its not extension-method) I'm a bit lost in googling around.

So is there a way to extend the error interface by a general method?

  • 写回答

2条回答 默认 最新

  • dousonghs58612 2018-08-08 13:45
    关注

    You can't extend error, it's a built-in interface type.

    You can extend your own interface types by simply adding new methods. This is "dangerous" at first, because implementing interfaces in Go is implicit: there is no declaration of intent. This means if you have a MyError interface, some existing types might already implement it and build on this. If you add a new method to it, existing types will most likely not implement it anymore, which will most likely break existing code (unless you add the implementation of that new method).

    Judging from the name of your wanted method (Check()), best would be to create a utility function:

    func check(err error) {
        if err != nil {
            panic(err) // Do something
        }
    }
    

    This "pattern" can be applied with your own interfaces too, it will not disturb existing implementations.

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

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口