Get Programming With Go
Get Programming With Go
Lesson 1
GETTING STARTED
Unit 4
Lesson 1 Get ready, get set, Go 3
COLLECTIONS
Unit 1
Lesson 16 Arrayed in splendor 121
Lesson 17 Slices: Windows into arrays 130
IMPERATIVE PROGRAMMING
Lesson 18 A bigger slice 138
Lesson 2 A glorified calculator 13 Lesson 19 The ever-versatile map 146
Lesson 3 Loops and branches 23 Lesson 20 Capstone: A slice of life 155
Lesson 4 Variable scope 34
Lesson 5 Capstone: Ticket to Mars 41 Unit 5
Unit 2 STATE AND BEHAVIOR
v
vi Contents
Unit 7
CONCURRENT PROGRAMMING
1
1 LESSON
3
4 Lesson 1 Get ready, get set, Go
The community of people who have adopted Go call themselves gophers, in honor of
Go’s lighthearted mascot (figure 1.1). Programming is challenging, but with Go and this
book, we hope you discover the joy of coding.
Consider this If you tell a digital assistant, “Call me a cab,” does it dial a taxi com-
pany? Or does it assume you changed your name to a cab? Natural languages like
English are full of ambiguity.
Clarity is paramount in programming languages. If the language’s grammar or syntax
allows for ambiguity, the computer may not do what you say. That rather defeats the
point of writing a program.
Go isn’t a perfect language, but it strives for clarity more so than any other language
we’ve used. As you go through this lesson, there will be some abbreviations to learn and
jargon to overcome. Not everything will be clear at first glance, but take the time to
appreciate how Go works to reduce ambiguity.
What is Go? 5
Go is crafted with a great deal of consideration for the experience of writing software.
Large programs compile in seconds with a single command. The language omits fea-
tures that lead to ambiguity, encouraging code that is predictable and easily under-
stood. And Go provides a lightweight alternative to the rigid structure imposed by
classical languages like Java.
Java omits many rarely used, poorly understood, confusing features of C++ that in our experience
bring more grief than benefit.
—James Gosling, Java: an Overview
Each new programming language refines ideas of the past. In Go, using memory effi-
ciently is easier and less error-prone than earlier languages, and Go takes advantage of
every core on multicore machines. Success stories often cite improved efficiency as a
reason for switching to Go. Iron.io was able to replace 30 servers running Ruby with
2 servers using Go (see mng.bz/Wevx and mng.bz/8yo2). Bitly has “seen consistent,
measurable performance gains” when rewriting Python apps in Go, and subsequently
replaced its C apps with a Go successor (see mng.bz/EnYl).
6 Lesson 1 Get ready, get set, Go
Go provides the enjoyment and ease of interpreted languages, with a step up in effi-
ciency and reliability. As a small language, with only a few simple concepts, Go is rela-
tively quick to learn. These three tenets form the motto for Go:
Go is an open source programming language that enables the production of simple, efficient,
and reliable software at scale.
—Go Brand Book
TIP When searching the internet for topics related to Go, use the keyword golang, which
stands for Go language. The -lang suffix can be applied to other programming languages as
well: Ruby, Rust, and so on.
If you click the Share button, you’ll receive a link to come back to the code you wrote.
You can share the link with friends or bookmark it to save your work.
QC 1.1 answer Large programs compile in seconds, and the Go compiler can catch typos and mis-
takes before running a program.
Packages and functions 7
NOTE You can use the Go Playground for every code listing and exercise in this book. Or, if
you’re already familiar with a text editor and the command line, you can download and install
Go on your computer from golang.org/dl/.
Quick check 1.2 What does the Run button do in The Go Playground?
When you visit the Go Playground, you’ll see the following code, which is as good a
starting point as any.
Though short, the preceding listing introduces three keywords: package, import, and func.
Each keyword is reserved for a special purpose.
The package keyword declares the package this code belongs to, in this case a package
named main. All code in Go is organized into packages. Go provides a standard library
comprised of packages for math, compression, cryptography, manipulating images, and
more. Each package corresponds to a single idea.
The next line uses the import keyword to specify packages this code will use. Packages
contain any number of functions. For example, the math package provides functions like
Sin, Cos, Tan, and Sqrt (square root). The fmt package used here provides functions for for-
matted input and output. Displaying text to the screen is a frequent operation, so this
package name is abbreviated fmt. Gophers pronounce fmt as “FŌŌMT!,” as though it
were written in the large explosive letters of a comic book.
QC 1.2 answer The Run button will compile and then execute your code on Google servers.
8 Lesson 1 Get ready, get set, Go
The func keyword declares a function, in this case a function named main. The body of
each function is enclosed in curly braces {}, which is how Go knows where each func-
tion begins and ends.
The main identifier is special. When you run a program written in Go, execution begins at
the main function in the main package. Without main, the Go compiler will report an error,
because it doesn’t know where the program should start.
Lux
tax
Delain
Money $400
chest
Cape
road
$60
To print a line of text, you can use the Println function (ln is an abbreviation for line).
Println is prefixed with fmt followed by a dot because it is provided by the fmt package.
Every time you use a function from an imported package, the function is prefixed with
the package name and a dot. When you read code written in Go, the package each func-
tion came from is immediately clear.
Run the program in the Go Playground to see the text Hello, playground. The text
enclosed in quotes is echoed to the screen. In English, a missing comma can change the
meaning of a sentence. Punctuation is important in programming languages too. Go
relies on quotes, parentheses, and braces to understand the code you write.
QC 1.3 answer
1 A program starts at the main function in the main package.
2 The fmt package provides functions for formatted input and output.
The one true brace style 9
Go is picky about the placement of curly braces {}. In listing 1.1, the opening brace { is
on the same line as the func keyword, whereas the closing brace } is on its own line. This
is the one true brace style—there is no other way. See mng.bz/NdE2.
To understand why Go became so strict, you
need to travel back in time to the birth of Go.
In those early days, code was littered with
semicolons. Everywhere. There was no escap-
ing them; semicolons followed every single
statement like a lost puppy. For example:
The compiler isn’t upset with you. A semicolon was inserted in the wrong place and it
got a little confused.
TIP As you work through this book, it’s a good idea to type the code listings yourself. You
may see a syntax error if you mistype something, and that’s okay. Being able to read, under-
stand, and correct errors is an important skill, and perseverance is a valuable trait.
10 Lesson 1 Get ready, get set, Go
Quick check 1.4 Where must opening braces { be placed to avoid syntax errors?
Summary
With the Go Playground you can start using Go without installing anything.
Every Go program is made up of functions contained in packages.
To print text on the screen, use the fmt package provided by the standard library.
Punctuation is just as important in programming languages as it is in natural lan-
guages.
You used 3 of the 25 Go keywords: package, import, and func.
fmt.Println("Hello, world")
fmt.Println("Hello, Ѝउ")
Go supports characters of every language. Print text in Chinese, Japanese, Rus-
sian, or Spanish. If you don’t speak those languages, you can use Google Trans-
late (translate.google.com) and copy/paste text into the Go Playground.
Use the Share button to get a link to your program and share it with other readers by
posting it on the Get Programming with Go forums (forums.manning.com/forums/get-
programming-with-go).
Compare your solution to the code listing in the appendix.
QC 1.4 answer An opening brace must be on the same line as func, rather than on an separate line.
This is the one true brace style.