Created
March 18, 2019 09:54
-
-
Save Maxibond/5da736727ae2c0231d1d44aed9b2685f to your computer and use it in GitHub Desktop.
Auto declared error in function has null access panic after checking if it is nil
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 struct { | |
error | |
} | |
func main() { | |
err := funcWithErrors() | |
fmt.Println(err) | |
} | |
func funcWithErrors() (err error) { | |
err = test(-1) | |
fmt.Println("-1 error: ", err) | |
if err != nil { | |
fmt.Println("-1 wow! ", err.Error()) | |
} | |
err = test(0) | |
fmt.Println("0 error: ", err) | |
if err != nil { // err is nil but the condition is true | |
fmt.Println("0 wow! ", err.Error()) // so we have a panic here coz null accessing | |
} | |
err = test(1) | |
fmt.Println("1 error: ", err) | |
if err != nil { | |
fmt.Println("1 wow! ", err.Error()) | |
} | |
return nil | |
} | |
func test(a int) *MyError { | |
if a >= 0 { | |
return nil | |
} else { | |
return &MyError{errors.New("negative")} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment