DEV Community

Kuldeep Singh
Kuldeep Singh

Posted on • Edited on • Originally published at programmingeeksclub.com

Important Rules of Go

Image description

Golang has strict coding rules that are there to help developers avoid silly errors and bugs in your golang code, as well as to make your code easier for other to read(for the Golang community).
This article will cover two such Important Rules of Golang you need to know of it.

1. Use of Golang package

Golang 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 program and you’ll understand after you try to execute it.

// First Important Rules of Golang
// never import any package which is
// not going to be used in the program
package main
import (
    "fmt"
    "log" // imported and not used log error
)
func main() {
    fmt.Println("Package log not used but is included in this program")
}
Enter fullscreen mode Exit fullscreen mode

If you execute your program(whatever name of the file), you will get the following error message from Golang and the program will not get execute.

Output:

~/important-rules-of-go$ go run main.go
# command-line-arguments
./main.go:8:2: imported and not used: "log"
Enter fullscreen mode Exit fullscreen mode

If you remove the log package from the import list of the program, it will compile just fine without any errors.
Let’s try to run program after removing log package from program.

// valid go program
package main
import (
    "fmt"
)
func main() {
    fmt.Println("Package log not used but is included in this program")
}
Enter fullscreen mode Exit fullscreen mode

If you execute this code you will not get any error on compile time.

Output:

~/important-rules-of-go$ go run main.go
Package log not used but is included in this program
Enter fullscreen mode Exit fullscreen mode

Although this is not the perfect time to start talking about breaking Golang rules, there is a way to bypass this restriction. This is showcased in the following code

// alternative way to bypass this 
// imported and not used rule
// just via adding underscore
// before the name of the package
// if you are not going to use that
// package
package main
import (
    "fmt"
    _ "log"
)
func main() {
    fmt.Println("Package log not used but is included in this program")
}
Enter fullscreen mode Exit fullscreen mode

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
If you execute the above code you’ll see no error as we got in before this example:

Output:

~/important-rules-of-go$ go run main.go
Package log not used but is included in this program
Enter fullscreen mode Exit fullscreen mode

You can read full article on this site
programmingeeksclub.com

Thanks for reading :)

Top comments (0)