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

huangapple go评论144阅读模式
英文:

Why Does Golang Allow Compilation of Unused Functions?

问题

私有/未导出的未使用函数可以被检测到。为什么编译器不像对待未使用的变量那样抱怨呢?

编辑:这个问题也适用于未使用的私有类型/接口。

英文:

Private/unexported functions not used could be detected. Why the compiler doesn't complain like it does for unused variables?

Edit: The question also applies to unused private types/interfaces too.

答案1

得分: 4

我相信这是作用域和默认接口{}的组合。

这就是为什么你可以在包级别声明一个未使用的变量,代码仍然可以正常构建的原因。

以下代码片段是有效的Go代码:

package main
import (
	"fmt"
	"time"
)

var (
	testVar = "sup"
)

func main() {
	start := time.Now()

	fmt.Println("This sure was a test")

	//Mon Jan 2 15:04:05 -0700 MST 2006
	fmt.Println("Finished!\nTimeElapsed:", time.Since(start))
}

即使变量testVar从未被使用,这段代码仍然有效。

这里有几个相关的问题,我认为它们都有相同的一般答案。

  • 为什么不允许未使用的变量?
  • 如果不允许未使用的变量,为什么允许未使用的函数参数?
  • 为什么允许未使用的函数/结构体?

一般的答案是,在函数作用域中未使用的变量要么是浪费编译器时间,要么是一个合法的错误,因此严格禁止未使用的变量。

然而,未使用的函数参数以及私有结构体和函数可能满足某个接口。至少它们都满足默认接口{}。因此,它们不一定是错误的。

目前似乎没有任何官方文档说明Go语言哲学中这个特定角落的原因,但正如在类似问题的答案中指出的那样,你可以在golang-nuts论坛上寻找答案和提问。

希望对你有所帮助!

英文:

I believe this is a combination of scope and the default interface {}.

This is the same reason that you can declare a variable at the package level that is unused and the code will build just fine.

This snippet is perfectly valid go code:

package main
import (
  "fmt"
  "time"
)

var (
  testVar = "sup"
)

func main() {
  start := time.Now()

  fmt.Println("This sure was a test")

  //Mon Jan 2 15:04:05 -0700 MST 2006
  fmt.Println("Finished!\nTimeElapsed:", time.Since(start))
}

<i>Even though</i> the variable <b>testVar</b> is never used.

There are several related questions here, and I think they all have the same general answer.

  • Why are unused variables not allowed?
  • Why are unused function parameters allowed if unused variables are not?
  • Why are unused functions/structs allowed?

...

The general answer is that unused variables in the scope of a function are ALWAYS either a waste of compiler time, or a legitimate error - so they are strictly not allowed.

However, unused function parameters, as well as private structs and functions, may satisfy an interface. At the very least they ALL satisfy the default interface {}. And as such, they are not at all guaranteed to be errors..

There doesn't appear to be any official documentation outlining the reasoning behind this particular corner of the golang philosophy, but as pointed out in the answer to a similar question you might have better luck finding answers and asking questions on the golang-nuts forum.

Hope this helps!

huangapple
  • 本文由 发表于 2015年9月14日 20:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/32564935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定