Why does Golang allow compilation of unused functions?

Private / inactive functions that are not used can be detected. Why doesn't the compiler complain about unused variables?

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

+6
source share
1 answer

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

This is the same reason you can declare a variable at the package level that is not used, and the code will be built just fine.

This piece of code is absolutely correct:

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 if the variable testVar is never used.

There are several related questions here, and I think they have a common answer.

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

...

The general answer is that unused variables in the scope of a function ALWAYS either lose compiler time or are a valid error - therefore, they are strictly forbidden.

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

It seems that there is no official documentation setting out the reasons behind this corner of the golang philosophy, but as indicated in an answer to a similar question, you might be lucky to find answers and ask questions on the golang nut forum .

Hope this helps!

+2
source

All Articles