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

标签 variables parameters compilation go

当来自 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/

相关文章:

c# - 为什么将 null 传递给 params 方法会导致空参数数组?

java - 如何运行已粘贴到我的程序中的 Java 代码

compilation - 我可以解析/编译 ChaiScript 脚本一次并调用它多次吗?

compilation - 如何控制cmake的子目录编译顺序?

php - Twig 用一个变量设置一个变量名 [TWIG/PHP]

powershell - 如何将变量存储到磁盘以便下次 PowerShell 脚本运行时可以使用它们?

python - 将 GET 请求中的 URL 发送到 Google App Engine 上的 Python 服务器

c# - 如何获取命令行参数并将其放入变量中?

python - 递归中的全局变量。 Python

c++ - 在 C++ 中比较参数和整数