有几个相关的问题在这里,我想他们都有相同的一般答案。
- 为什么不使用未使用的变量?
- 如果未使用的变量为不是?
- 为什么允许使用未使用的函数/结构体?
...
一般的答案是,函数作用域中未使用的变量总是浪费编译器时间或合法错误 - 所以严格禁止它们。
然而,未使用的函数参数以及私有结构和函数可能会满足一个接口。至少它们都满足默认界面{}。因此,他们一点也不保证是错误的。
似乎没有任何官方文件概述了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屋!