Strange error in Go: 'fmt.Println not used'

· 305 Words

I had a mysterious error in a project in Go:

myproject/types.go:89: fmt.Println not used

If you declare a variable or import a package in Go, that’s a compiler error. Good thing too, in my opinion. But this one was puzzling. It wasn’t complaining about an imported package, it was complaining about a function within a package. As far as I’m aware, the syntax of Go allows only for importing a whole package (or sub-package) at a time, rather than members of that package (as Python does).

The odd thing was that the error was reported on the last line of the file. The entire contents of that line was:

}

I removed every reference to fmt in types.go as instructed, and the error persisted. I moved code out of the file until I was left with an empty file (except the package statement) and still the error was showing up for that file(!).

types2.go:

package mypackage
import (
)

and when I built it:

go build mypackage # mypackage ./types2.go:4: fmt.Println not used

As I re-shuffled and removed and re-included files the error jumped from file to file. The Go compiler reported this in no fewer than 3 files including the enigmatic epoch, whatever that is:

<epoch>: fmt.Println not used

I thought this might be a compiler error (they’re not unheard of) and headed over to StackOverflow. No luck there. I even upgraded from version 1.0.1 to version 1.0.2.

Finally I found the problem. I had half-typed and forgotten the following line in a function:

fmt.Println

and then forgotten about it. Go never mentioned an error in that file. Easily fixed, and the error went away.

But a confusing error, as it was reported in every file other than the one I was using it in. Perhaps it’s a compiler bug after all, of sorts.

Read more