Careful when comparing value with nil in Golang

func main() {

err := Foo()

fmt.Println(err == nil)
}
func Foo() error {
var err *os.PathError =nil
return err
}
/tmp/___go_build_main_go #gosetup false Process finished with exit code 0




Best practice

func main() {
err := Foo()
fmt.Println(err == nil)
}
func Foo() error {
var err *os.PathError =nil
if err!= nil {
return errors.New("Not nil")
}
return nil
}

/tmp/___go_build_main_go #gosetup
true

Process finished with exit code 0

Comments

Post a Comment

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch