当来自 C 语言时,Go 的一个更值得注意的方面是,如果在其中声明了一个未使用的变量,编译器将不会构建您的程序。那么,如果函数中声明了一个未使用的参数,为什么还要构建这个程序呢?
func main() {
print(computron(3, -3));
}
func computron(param_a int, param_b int) int {
return 3 * param_a;
}
最佳答案
官方没有给出原因,但是在golang-nuts上给出的原因是:
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
有时具有未使用的参数对于满足接口(interface)很重要,一个示例可能是在加权图上运行的函数。如果你想在所有边上实现一个成本一致的图,考虑节点是没有用的:
func (graph *MyGraph) Distance(node1,node2 Node) int {
return 1
}
正如该线程所指出的,有一个有效的参数只允许名为 _
的参数如果它们未被使用(例如 Distance(_,_ Node)
),但此时为时已晚,因为 Go 1 future-compatibility guarantee .正如也所提到的,一个可能的反对意见是参数,即使未使用,也可以隐式提供文档。
简而言之:没有具体的、具体的答案,只是他们最终只是做出了一个武断的(但仍然有根据的)决定,即未使用的参数比未使用的局部变量和导入更重要和有用。如果曾经有一个强有力的设计理由,那么它不会记录在任何地方。
关于variables - 为什么 Go 允许编译未使用的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549228/