Welcome to this free digital book on the Go programming language! It is divided into several topics to provide a complete overview of Go, its features, and what can be created with it.
This book tries to provide a step-by-step tutorial for complete beginners - yet it can be used by developers with existing Go experience to refresh knowledge or learn new concepts.
No long talk. Let’s dive into this amazing language!
Installing Go
Installing the Go programming language can be done here: https://go.dev/doc/install
Once you have completed the installation, type the following into your terminal to see if Go is working:
Ideally, an output like go version go1.22.2 darwin/amd64
should appear. You are good to go!
Hello world in Go
Once your environment is set up, you’re ready to write your first Go program. Here’s how you can write the classic “Hello World”:
- Create a New File: Inside your directory of choice, create a new file named
hello.go
. - Write the Code: Open
hello.go
in your editor and type the following Go code:
- **Let’s understand what is happening here:
package main
: This line defines the package name. Every Go program starts with a package declaration. Programs that are executable start withpackage main
.import "fmt"
: This line tells the Go compiler to include thefmt
package, which contains functions for formatted I/O operations (like printing text to the console).func main()
: Themain
function is the entry point of the program. When you run the Go program, the code inside themain
function executes.fmt.Println("Hello, world!")
: This line outputs the string “Hello, world!” to the console.Println
is a function from thefmt
package that prints its arguments followed by a new line.
Running the Program
To run your Go program, follow these steps:
- Open a Terminal/Command Prompt: Navigate to your directory where your
hello.go
file is located. - Run the Program: Type
go run hello.go
and press Enter. The Go toolchain will compile and execute your program, and you should see “Hello, world!” printed in the terminal.
Great! You executed your first program in Go.
Next Chapter: Datatypes in Go