Why does Go allow compilation of unused function parameters?

There’s no official reason, but the reason given on golang-nuts is:

Unused variables are always a programming error, whereas it is common
to write a function that doesn’t use all of its arguments.

One could leave those arguments unnamed (using _), but then that might
confuse with functions like

func foo(_ string, _ int) // what’s this supposed to do?

The names, even if they’re unused, provide important documentation.

Andrew

https://groups.google.com/forum/#!topic/golang-nuts/q09H61oxwWw

Sometimes having unused parameters is important for satisfying interfaces, one example might be a function that operates on a weighted graph. If you want to implement a graph with a uniform cost across all edges, it’s useless to consider the nodes:

func (graph *MyGraph) Distance(node1,node2 Node) int {
    return 1
}

As that thread notes, there is a valid argument to only allow parameters named as _ if they’re unused (e.g. Distance(_,_ Node)), but at this point it’s too late due to the Go 1 future-compatibility guarantee. As also mentioned, a possible objection to that anyway is that parameters, even if unused, can implicitly provide documentation.

In short: there’s no concrete, specific answer, other than that they simply made an ultimately arbitrary (but still educated) determination that unused parameters are more important and useful than unused local variables and imports. If there was once a strong design reason, it’s not documented anywhere.

Leave a Comment