为什么Golang允许编译未使用的函数? [英] Why Does Golang Allow Compilation of Unused Functions?

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

问题描述

可以检测到未使用的私有/未导出的功能。为什么编译器不会像为未使用的变量一样抱怨?



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

解决方案

我相信这是范围和默认界面的结合{/}。
$ b 这是原因是你可以在包级别声明一个未使用的变量,并且代码可以很好地构建。



这段代码非常有效go code:

 包主
导入(
fmt
时间


var(
testVar =sup


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

fmt.Println(This sure a test)

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

尽管变量 testVar 从未被使用过。



有几个相关的问题在这里,我想他们都有相同的一般答案。


  • 为什么不使用未使用的变量?

  • 如果未使用的变量为不是?

  • 为什么允许使用未使用的函数/结构体?



...



一般的答案是,函数作用域中未使用的变量总是浪费编译器时间或合法错误 - 所以严格禁止它们。



然而,未使用的函数参数以及私有结构和函数可能会满足一个接口。至少它们都满足默认界面{}。因此,他们一点也不保证是错误的。



似乎没有任何官方文件概述了golang这个角落背后的推理哲学,但正如对类似问题的回答所指出的那样,您可能会找到更好的答案并在< a href =https://groups.google.com/forum/#!forum/golang-nuts =nofollow noreferrer> golang-nuts论坛。

希望这有助于!


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.

解决方案

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))
}

Even though the variable testVar 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!

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

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