Go has strict rules about package usage. Therefore, you cannot just include any package you might think that you will need and then not use it afterward.
Look at the following naive program, which is saved as packageNotUsed.go:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello there!")
}
In this book, you are going to see lots of error messages, error situations, and warnings. I believe that looking at code that fails to compile is also useful and sometimes even more valuable than just looking at Go code that compiles without any errors. The Go compiler usually displays useful error messages and warnings that will most likely help you to resolve an erroneous situation, so do not underestimate Go error messages and warnings.
If you execute packageNotUsed.go, you will get the following error message from Go and the program will not get executed:
$ go run packageNotUsed.go
# command-line-arguments
./packageNotUsed.go:5:2: imported and not used: "os"
If you remove the os package from the import list of the program, packageNotUsed.go will compile just fine; try it on your own.
Although this is not the perfect time to start talking about breaking Go rules, there is a way to bypass this restriction. This is showcased in the following Go code that is saved in the packageNotUsedUnderscore.go file:
package main
import (
"fmt"
_ "os"
)
func main() {
fmt.Println("Hello there!")
}
So, using an underscore character in front of a package name in the import list will not create an error message in the compilation process even if that package will not be used in the program:
$ go run packageNotUsedUnderscore.go
Hello there!
The reason that Go is allowing you to bypass this rule will become more evident in Chapter 6, What You Might Not Know About Go Packages and Go Functions.