Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 7, 2022 02:01 pm GMT

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 youll 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 programpackage mainimport (    "fmt"    "log" // imported and not used log error)func main() {    fmt.Println("Package log not used but is included in this program")}

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"

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

// valid go programpackage mainimport (    "fmt")func main() {    fmt.Println("Package log not used but is included in this program")}

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

Output:~/important-rules-of-go$ go run main.goPackage log not used but is included in this program

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// packagepackage mainimport (    "fmt"    _ "log")func main() {    fmt.Println("Package log not used but is included in this program")}

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 youll see no error as we got in before this example:

Output:~/important-rules-of-go$ go run main.goPackage log not used but is included in this program

You can read full article on this site
programmingeeksclub.com

Thanks for reading :)


Original Link: https://dev.to/mavensingh/important-rules-of-go-3hg7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To