Chapter 2. Primitive Types and Declarations

Now that we have our development environment set up, it’s time to start looking at Go’s language features and how to best use them. When trying to figure out what “best” means, there is one overriding principle: write your programs in a way that makes your intentions clear. As we go through features, we’ll look at the options and I’ll explain why I find a particular approach produces clearer code.

We’ll start by looking at primitive types and variables. While every programmer has experience with these concepts, Go does some things differently, and there are subtle differences between Go and other languages.

Built-in Types

Go has many of the same built-in types as other languages: booleans, integers, floats, and strings. Using these types idiomatically is sometimes a challenge for developers who are transitioning from another language. We are going to look at these types and see how they work best in Go. Before we review the types, let’s cover some of the concepts that apply to all types.

The Zero Value

Go, like most modern languages, assigns a default zero value to any variable that is declared but not assigned a value. Having an explicit zero value makes code clearer and removes a source of bugs found in C and C++ programs. As we talk about each type, we will also cover the zero value for the type.

Literals

A literal in Go refers to writing out a number, character, or string. There are four common kinds of literals ...

Get Learning Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.