I was playing around with the html/template package in a small Go project when I stumbled across the following line of code.
t := template.Must(template.ParseFS(fs, path))
I am sure I copied this from a book or tutorial at some point in the past. I have always found this usage template.Must
to be confusing. The documentation states that it takes two parameters, but it appears I only pass it one!
Inspection of the return type template.ParseFS
shows it returns multiple values, and its output matches the required input for template.Must
. It struck me that the output from one function was being spread across the inputs of another.
I felt as if this was a language feature of which I was unaware. I set out to find some documentation and found this gem in the Go Programming Language Specification:
As a special case, if the return values of a function or method
g
are equal in number and individually assignable to the parameters of another function or methodf
, then the callf(g(parameters_of_g))
will invokef
after binding the return values ofg
to the parameters off
in order. The call off
must contain no parameters other than the call ofg
, andg
must have at least one return value. Iff
has a final...
parameter, it is assigned the return values ofg
that remain after assignment of regular parameters.
I will likely use this sparingly because this special case is not intuitive. However, I think it can be used to make code more terse. In the case of template.Must
above, it saves me from creating an error variable.