Did I find an error in the blog?

I’m taking the go-tour and read https://blog.golang.org/defer-panic-and-recover

There I see the example:

src, err := os.Open(srcName)
if err != nil {
    return
}
defer src.Close()

Shouldn’t the defer come before the if?

src, err := os.Open(srcName)
defer src.Close()
if err != nil {
    return
}

No, because src will be nil in this case. Defering Close on it only makes sense if there is no error.

4 Likes

Thanks for clarification.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.