且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Go允许编译未使用的函数参数?

更新时间:2023-09-17 19:51:46

没有官方理由,在golang-nuts上给出的原因是:

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)//这应该做什么?

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

如果未使用,请提供重要的文件。

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

Andrew

a href =https://groups.google.com/forum/#!topic/golang-nuts/q09H61oxwWw> https://groups.google.com/forum/#!topic/golang-nuts/q09H61oxwWw

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
}

正如该线程笔记,有一个有效的参数只允许名为 _ 的参数,如果它们未被使用(例如 Distance )),但由于 Go 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.