2 Go Crash Course

 

This chapter covers

  • Packages and modules.
  • Variables and pointers.
  • Collection types: arrays, slices, and maps.
  • Object-oriented programming.
  • Concurrent programming.
  • Error handling.

This chapter is a fast-paced primer for experienced programmers to prepare for the more advanced content we cover in the book. While other chapters focus on idiomatic Go and testability, this chapter focuses on the basics of Go's distinctive features and mechanics.

Treat this chapter as a warm-up rather than a mastery. Use it as reference material and return to it as you read the book. And don't worry if some of the content in this chapter is challenging to understand, as it'll become clearer as you progress in the book.

Note

The source code of this chapter is at the link: https://github.com/inancgumus/gobyexample/tree/main/basics

2.1 Packages

We'll start with a simple executable program example that prints this book's title.

This is our program's directory structure:

.                -> The project's root directory (new directory)
├── go.mod       -> Defines our project's name and dependencies
├── hello.go     -> Implements the package main
└── book         -> The book package's directory
    └── book.go  -> Implements the book package

Let's create a new directory on our system. We can create the rest later.

2.1.1 Overview

In Go, we write our code inside packages. There are two kinds of packages:

2.1.2 Importable packages

2.1.3 Package main

2.1.4 Modules

2.1.5 Building and running

2.1.6 Exercises

2.1.7 Wrap up

2.2 Pointers

2.2.1 Variables and pointers

2.2.2 Address operators

2.2.3 Pass by value mechanics

2.2.4 Exercises

2.2.5 Wrap up

2.3 Collections

2.3.1 Arrays

2.3.2 Slices

2.3.3 Maps

2.4 Object-oriented programming

2.4.1 Structs

2.4.2 Methods and receivers

2.4.3 Implicit interfaces

2.4.4 Wrap up

2.5 Concurrency

2.5.1 Goroutines

2.5.2 Channels

2.5.3 Practice

2.5.4 Goroutine leaks

2.5.5 Multiple channel operations

2.5.6 Timers to the rescue

2.5.7 Exercises

sitemap