-2

I've recently watch this talk by Liz Rice (which I highly recommend!), and I've seen that instead of writing:

func main() {
    if err := someFunc(); err != nil {
        panic(err)
    }
}

she does:

func main() {
    must(someFunc())
}

func must(err error) {
    panic(err)
}

Is it an idiomatic way to handle errors? IMO it does not improve readability, and I feel that it does not follows the Go proverb "Clear is better than clever". What do you think?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
hacb
  • 175
  • 2
  • 10
  • 2
    A generic function like the one presented is not idiomatic, however there are some packages even in the std lib that provide a `Must` func to simplify initialization, see for example `html/template`. – mkopriva Mar 01 '21 at 07:31
  • 2
    I think you have to consider _how_ that must() function is used. It is used in the context of a talk with slides / live coding, so being as terse as possible is important. On the other hand, in production, randomly panicing is not a good idea :-) – marco.m Mar 01 '21 at 07:40
  • yeah, I guess it is easier to use `must()` while live-coding :) – hacb Mar 01 '21 at 07:48
  • Iff panicing is the right way to "handle" these types of "errors" then yes, if not then not. – Volker Mar 01 '21 at 07:55

1 Answers1

4

The MustXXX(error) pattern is useful when the error could arise at runtime, but whether it does is actually decided at compile time. Meaning if the source code is what it should be, the error will not happen at runtime.

Shining examples are template.Must() and regexp.MustCompile(). If you provide a valid template or valid regexp in the source code, parsing them will never fail at runtime. In these situations using Must() results in shorter and clear code. Tests should be supplied to detect if invalid template or regexp is used in the source, so the mistake is detected early (when tests are run).

Other than that (when an error could happen based on runtime conditions like user input, data read from external source etc.), the Must() pattern is obviously not advised and you should handle the error properly.

See related: Multiple values in single-value context

icza
  • 389,944
  • 63
  • 907
  • 827