Getting started in Go
Installing Go
Section titled “Installing Go”Getting started with Go is easy. Go to go.dev and install the Go compiler for your machine. In case you don’t want to install anything locally, you can get started with Go in Docker too. (Fun fact: Docker was written in Go)
When your installation was successful, you can check Go’s version in your terminal with:
go versionHello world in Go
Section titled “Hello world in Go”On your machine, create a file called app.go. Once created, past the following code into it:
package main // a package must be defined
import "fmt"
func main() { fmt.Println("Hello World!")}To execute it and see “Hello World!” written in the terminal, run:
go run app.goWhen you want to compile your little Go programm, run:
go build app.go./app.goOn Windows, it will create a .exe file, which is to be executed differently.
Understanding Go’s structure
Section titled “Understanding Go’s structure”Before you play around with Go more, I’d like to emphasize some basis rules of Go.
main and init function
Section titled “main and init function”As you might have noticed, there is a main-function in our Hello world example as we know it from C or C++. Just like in C/C++, the main function is executed automatically and therefore necessary as an entry point. Keep in mind each package of Go must have a single main-function.
Next to main(), there can be multiple functions called init(), which are optional. As you can create more than one init function, they are called in order of their creation.
package main // a package must be defined
import "fmt"
func init() { fmt.Println("first init")}
func init() { fmt.Println("second init")}
func main() { fmt.Println("Hello World!")}output:
first initsecond initHello World!What imperatively means
Section titled “What imperatively means”Go is an imperative programming language, which means the code consists of commands, which are executed from top to bottom. In Go, it is important to not use data before its initialization. The example below leads to an error
func main() { fmt.Println(num) var num int = 10}