I would agree with jnml's answer that they are both idiomatic code, and add the following:
Your first example:
if err != nil {
//handle err
}
is more idiomatic when dealing with more than one return value. for example:
val, err := someFunc()
if err != nil {
//handle err
}
//do stuff with val
Your second example is nice shorthand when only dealing with the err
value. This applies if the function only returns an error
, or if you deliberately ignore the returned values other than the error
. As an example, this is sometimes used with the Reader
and Writer
functions that return an int
of the number of bytes written (sometimes unnecessary information) and an error
:
if _, err := f.Read(file); err != nil {
//handle err
}
//do stuff with f
The second form is referred to as using an if initialization statement.
So with regards to best practices, as far as I know (except for using the "errors" package to create new errors when you need them) you've covered pretty much everything you need to know abut errors in Go!
EDIT: If you find you really can't live without exceptions, you can mimic them with defer,panic & recover.