Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does Golang Allow Compilation of Unused Functions?

Tags:

go

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.

like image 337
Anthony Hunt Avatar asked Sep 14 '15 12:09

Anthony Hunt


1 Answers

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!

like image 101
Opnauticus Avatar answered Oct 10 '22 01:10

Opnauticus