Go's Special Case for Function Calls
Posted on June 5, 2022
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
gare equal in number and individually assignable to the parameters of another function or method
f, then the call
fafter binding the return values of
gto the parameters of
fin order. The call of
fmust contain no parameters other than the call of
gmust have at least one return value. If
fhas a final
...parameter, it is assigned the return values of
gthat 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.