Created
July 13, 2023 16:56
-
-
Save fcracker79/4f9d63106ad4c422d4f440450da18060 to your computer and use it in GitHub Desktop.
Play with interfaces and zero-value objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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