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 g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g 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.