Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcracker79/4f9d63106ad4c422d4f440450da18060 to your computer and use it in GitHub Desktop.
Save fcracker79/4f9d63106ad4c422d4f440450da18060 to your computer and use it in GitHub Desktop.
Play with interfaces and zero-value objects
package main
import (
"errors"
"fmt"
)
type MyError string
func (e MyError) Error() string {
return string(e)
}
const Err1 = MyError("Err1")
func genErr(f bool) error {
var e error
if f {
e = Err1
}
return e
}
func genErrSpecificType(f bool) error {
var e MyError
if f {
e = Err1
}
return e
}
func playWithNilErrors() {
// true
fmt.Println(genErr(false) == nil)
// false
fmt.Println(genErr(true) == nil)
// false <- error is an interface. Its nil value has no such type. But the variable inside
// `genErrSpecificType` is declared as MyError, which has a type. So it is not nil.
fmt.Println(genErrSpecificType(false) == nil)
// false
fmt.Println(genErrSpecificType(true) == nil)
}
func main() {
playWithNilErrors()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment