I recently started learning Go and thought it'd be helpful to break down how to write the traditional Hello World Program and what the code chunks mean.
First, you have to set up your Go environment. I use VS Code as my IDE of choice, but you can also practice this in the Golang playground (like CodePen, but for Go).
After you've set up your code editor and your first Go file, you will want to copy and paste this piece of code:
Once you run this, you'll get the output, "Hello World", which is pretty neat.
However, what do all these pieces of code mean? In the next paragraphs, we'll take this small program apart and explain what each line does.
To begin, the package main bit here refers to how the Go compiler knows that the package should be compiled as an executable program. Every Go file starts with this "package package_name" statement.
Essentially, packages help you compile Go files into one unit that allows you easily reuse pieces of code. They are like a directory or folder that holds your Go source files.
In this piece of code, the package name main is used here. Go programs start running in the main package. It is a special package that is used with programs that are meant to be executable.
Next, we have the import statement, import "fmt", which is used to import other packages into our program. Here, the fmt package is imported to be used inside the main function so we can print out text.
After that, we've got our function, func main(). In Go, the keywords, func funcname() are used to define a function. Here, the main function is special because the entire program starts execution from it. The curly braces also denote the beginning and end of a function.
The last part of this code chunk is the print function here: fmt.Println("Hello World"). To call a function in a package in Go, you will want to use the syntax, package.function(). Since we already have our fmt package, we use that to write text to the output.
So, that's a quick breakdown of all the code it takes to write a Hello World program in Go. If you'd like to follow my Go learning journey, I'm over at @tbrmonster on Twitter. Thank you for reading! :)