Reputation: 3282
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?
Upvotes: 2
Views: 1803
Reputation: 19
I would highly suggest to use casual if statement for error checking.
if err != nil {
log.Printf("Error received - [%v]",err)
return err
}
Because golang doesn't have try catch block familiar to C#.
And if your method Check() will return bool - you will still need to check it against the if statement.
Upvotes: 0
Reputation: 417592
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.
Upvotes: 6