Skip to content

Instantly share code, notes, and snippets.

@Maxibond
Created March 18, 2019 09:54
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 Maxibond/5da736727ae2c0231d1d44aed9b2685f to your computer and use it in GitHub Desktop.
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
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