为什么 Go 允许编译未使用的函数参数? [英] Why does Go allow compilation of unused function parameters?

查看:23
本文介绍了为什么 Go 允许编译未使用的函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当来自 C 语言时,Go 的一个更值得注意的方面是,如果在其中声明了一个未使用的变量,编译器将不会构建您的程序.那么,如果在函数中声明了一个未使用的参数,那么为什么要构建这个程序呢?

One of the more notable aspects of Go when coming from C is that the compiler will not build your program if there is an unused variable declared inside of it. So why, then, is this program building if there is an unused parameter declared in a function?

func main() {
    print(computron(3, -3));
}


func computron(param_a int, param_b int) int {
    return 3 * param_a;
}

推荐答案

官方没有给出原因,但是在 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.

安德鲁

https://groups.google.com/forum/#!主题/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(_,_ Node)),但在这一点上为时已晚,因为 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.

这篇关于为什么 Go 允许编译未使用的函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆