100% found this document useful (4 votes)
180 views

Download Complete Go by Example MEAP Programmer s guide to idiomatic and testable code Inanc Gumus PDF for All Chapters

Programmer

Uploaded by

basiqzolver
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
180 views

Download Complete Go by Example MEAP Programmer s guide to idiomatic and testable code Inanc Gumus PDF for All Chapters

Programmer

Uploaded by

basiqzolver
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Download the full version of the ebook at ebookfinal.

com

Go by Example MEAP Programmer s guide to idiomatic


and testable code Inanc Gumus

https://ebookfinal.com/download/go-by-example-meap-
programmer-s-guide-to-idiomatic-and-testable-code-inanc-
gumus/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookfinal.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Ruby by Example Concepts and Code 1st Edition Kevin C.


Baird

https://ebookfinal.com/download/ruby-by-example-concepts-and-code-1st-
edition-kevin-c-baird/

ebookfinal.com

Go in Practice Second Edition MEAP V02 Nathan Kozyra

https://ebookfinal.com/download/go-in-practice-second-edition-
meap-v02-nathan-kozyra/

ebookfinal.com

XNA 4 0 Game Development by Example Beginner s Guide


Visual Basic Edition Kurt Jaegers

https://ebookfinal.com/download/xna-4-0-game-development-by-example-
beginner-s-guide-visual-basic-edition-kurt-jaegers/

ebookfinal.com

Silverlight 3 Programmer s Reference Wrox Programmer to


Programmer 1st Edition J. Ambrose Little

https://ebookfinal.com/download/silverlight-3-programmer-s-reference-
wrox-programmer-to-programmer-1st-edition-j-ambrose-little/

ebookfinal.com
USB Design by Example A Practical Guide to Building I O
Devices 2nd Edition John Hyde

https://ebookfinal.com/download/usb-design-by-example-a-practical-
guide-to-building-i-o-devices-2nd-edition-john-hyde/

ebookfinal.com

Information Theory and Coding by Example Kelbert Mark

https://ebookfinal.com/download/information-theory-and-coding-by-
example-kelbert-mark/

ebookfinal.com

Systems programmer s guide to z OS System Logger 1st ed


Edition Ibm Redbooks

https://ebookfinal.com/download/systems-programmer-s-guide-to-z-os-
system-logger-1st-ed-edition-ibm-redbooks/

ebookfinal.com

SAS Functions by Example Second Edition Ron Cody

https://ebookfinal.com/download/sas-functions-by-example-second-
edition-ron-cody/

ebookfinal.com

Python Machine Learning by Example Yuxi (Hayden) Liu

https://ebookfinal.com/download/python-machine-learning-by-example-
yuxi-hayden-liu/

ebookfinal.com
Go by Example
1. welcome
2. 1_Getting_Started
3. 2_Go_Crash_Course
4. 3_Idiomatic_Testing
5. 4_Test_Coverage_and_Performance_Optimization
6. 5_Structuring_Command-Line_Programs
7. 6_Testable_Command-Line_Programs
8. 7_Structuring_Concurrent_Pipelines
9. 8_Context,_HTTP,_and_Testing
10. 9_Structuring_HTTP_Servers
11. 10_Functional_Programming_with_Middleware
12. 11_Database_and_Integration_Testing
welcome
Thanks for purchasing the MEAP for Go by Example: Programmer's guide to
idiomatic and testable code. If you want to write Go code that’s easy to
maintain and extend, you’ve come to the right place!

To get the most benefit from this book, you’ll need to be an experienced
developer with an intermediate knowledge of testing in any language. You
may be new to Go, but knowing the basics will help along the way.

As I write this, there’s no book yet on testing in Go, but there’s a growing
need for developers. Go is a young language, and hundreds of thousands of
developers from other programming languages come to Go every year. If
you’re one of them, you may be wondering how to transfer your existing
knowledge of other languages, particularly when it comes to testing.

This book will teach you how to implement practical, real-life Go projects
with tests from scratch. I’ll be showing you different testing approaches—
what to do, what not to do, and when and why you should use a particular
method using real-life, practical examples you might encounter in the
workplace.

I got the idea for this book based on questions I received from folks who’ve
taken my Udemy course or are following my blog. Idiomatic Go will answer
these questions and more:

How can I test in Go?


How can I test my program?
What should I test—or not test?
Am I testing correctly? What are the best practices?
What makes Go tests and tests in other programming languages
different?
How can I build an easy to maintain Go program from scratch with
tests?
All said, I hope you enjoy this book and that you find it useful to your own
programming practice. If you have any questions, comments, or suggestions,
please share them in Manning’s liveBook Discussion forum for my book.
And, if you want to stay up to date on all the latest Go test best practices, be
sure to give my Twitter a follow.

Let’s get started with Go testing together!

—Inanc Gumus

In this book

welcome 1 Getting Started 2 Go Crash Course 3 Idiomatic Testing 4 Test


Coverage and Performance Optimization 5 Structuring Command-Line
Programs 6 Testable Command-Line Programs 7 Structuring Concurrent
Pipelines 8 Context, HTTP, and Testing 9 Structuring HTTP Servers 10
Functional Programming with Middleware 11 Database and Integration
Testing
1 Getting Started
This chapter covers
Importance of writing idiomatic and testable code
Introducing Go's big features

Go is a modern and simple programming language that makes it convenient


for individuals and distributed teams to work together to develop efficient,
adaptable, maintainable, and scalable software that harnesses the full power
of today's multi-core CPU systems. It's a perfect language for developing
command-line tools, network programs, and so on.

This chapter explores the book's goals, introduces Go, and showcases Go's
big features without fully delving into Go's mechanics and idioms (I'll leave
the details to other chapters).

Let's take a look at why you should read this book and what you can expect
from it.

1.1 Why should you read this book?


Getting up to speed with Go is so straightforward that in 2020, I tweeted:

"Go is easy to learn. Hard to master."

While most programming languages can be difficult to master, Go is one of


the few that is relatively easy to learn. Experienced programmers can learn
the basics of Go in just a week. Yet, using Go to its full potential requires a
deep understanding of its idioms and mechanics.

So, this book has two goals:

1. Crafting idiomatic and readable in Go.


2. Crafting testable and maintainable code in Go.
Rather than the usual boring examples like foo, bar, and baz, or Person,
Animal, etc. this book aims to teach how to craft idiomatic and testable Go
code from scratch with real-world examples. With this approach of learning
by examples, you will clearly see why and when to use Go's features without
worrying about making common mistakes beginners make.

Together, we'll explore command-line tools, design concurrent programs,


structure HTTP servers, and clients, and effectively use interfaces to write
adaptable code.

Each chapter includes examples and exercises that allow you to code along
with the book and cement what you learn. In my thirty years of programming
experience, that's the best way to learn another programming language or
anything else.

I'm writing this book for intermediate-level programmers experienced in


another language but new to Go. Those with experience in Go might also find
what the book explores enlightening. I won't talk much about the basics of
programming, so you also need basic programming skills like arrays, hash
tables, etc., but you don't need to be a computer scientist. Knowing a bit or
two about computer CPU and memory work will help.

Let's continue with this book's primary goals: crafting idiomatic and testable
code. Then, we'll dive into Go's distinctive and flagship features. By the end
of this book, you'll be knowledgeable enough to start using Go effectively in
your projects.

Note

You can follow me for Go tips, tricks, and updates: https://x.com/inancgumus

1.2 Crafting idiomatic code


"Programs are meant to be read by humans and only incidentally for
computers to execute."

— H. Abelson and G.J. Sussman, from the book Structure and Interpretation
of Computer Programs

Writing complex code is easy. However, achieving simplicity is not. The


puzzle's missing piece is combining the correct pieces to craft meaningful,
expressive, yet powerful code.

The good news is that there is a recommended approach called "Idiomatic


Go," which means the best practices for crafting Go code. By following
idiomatic practices, you can improve the maintainability and
understandability of your code.

Here is what idiomatic Go code looks like:

Simple—Code is straightforward to understand.


Readable—Code is easy to read (readability is better than clever code).
Explicit—Code can be read from top to bottom without making many
assumptions about how it works. Each line tells us the cost of the
underlying operation.
Pragmatic—Code is concrete and solves today's problems. There are no
unnecessary abstractions that can make the code harder to understand.
Testable—Code is straightforward to test.

Achieving these qualities is not a walk in the park. The journey from learning
to mastering Go can be quite the ride. To create idiomatic code in Go, you
must understand the language mechanics. Otherwise, you'll fight with the
language and bring your past knowledge from other programming languages
to Go. Doing so will eventually bite and frustrate you.

Throughout this book, you'll discover insights and techniques to help you
write high-quality idiomatic code in Go. What this book discusses will give
you the proper mindset and set you on the right path to achieving your goals
faster and reliably with Go.

Still, there is no single truth but guidelines.

Some people can look at the same code and think, "Oh, this is terrible!"
while others may think, "This is awesome!" Ultimately, it's about creating
code that can survive by quickly adapting to changing needs, which brings us
to our next goal: writing testable code.

1.3 Crafting testable code


"Nothing endures but change."

— Heraclitus

Testable code has superpowers.

It's a shape-shifter, capable of adapting to new requirements and standing the


test of time. However, software that resists change loses this crucial ability.
With automated tests, you can confidently determine if our code works
correctly even after modifications.

But even with tests, developing an entirely bug-free program is challenging.


Our tests might have touched every line of the program, but they most likely
didn't test every possible path. So, 100% test coverage doesn't mean our
programs are bug-free.

Finding bugs is only one side of the testing story. Equally important is
creating testable code—an art form in its own right. Testable code also tends
to be easily adaptable. You can forge resilient, adaptable, and well-designed
programs with testable code. When you write tests, you effectively put our
code through its paces from the perspective of those tests. This allows us to
experience firsthand how easy or challenging it is to interact with our code.

Lastly, tests can help us but should not be our end goal. Testing should be
pragmatic, and you should not test just for the sake of testing. If you take
testing too far, you might go to the extreme end of the testing spectrum.
There is a thin line there. Luckily, we'll discover where that line starts and
ends and explore pragmatic and reliable solutions.

Each chapter in the book is crafted to provide insights into the world of
testable code. You may notice variations in the number of tests presented in
different chapters. In Chapters 3 and 4, the emphasis is on testing itself to
explain the fundamentals. As you progress in the book, discussions will shift
toward writing idiomatic and inherently testable code. While the latter
chapters may contain fewer tests, they dive into writing testable code.

Now that you know the book's goals, the rest of the chapter will focus on Go
itself. Let's start with a short history of Go to understand why Go exists.
Then, the chapter will briefly introduce Go's flagship features, such as
concurrency and interfaces.

1.4 Why does Go exist?


In 2007, seasoned programmers came together to create Go:

Ken Thompson (instrumental in the creation of the C language and


UTF-8).
Rob Pike (co-inventor of UTF-8).
Robert Griesemer.

Russ Cox (now the tech lead of Go) and Ian Lance Taylor would join the
team shortly after.

They aimed to address the issues they faced with other languages: slow
compilation times and complex, cumbersome features in efficient languages
like C, C++, and Java, as well as the lack of efficiency in developer-friendly
languages like Python and JavaScript. They aimed to blend the best features
of static and dynamic languages into a new one.

After five years of development, Go was released. It offered a solution that


balanced simplicity, reliability, and efficiency in software development. This
balance is a key reason for Go's success, appealing to developers and
companies worldwide, including tech giants like Amazon, Apple, Google,
and others, who now rely on Go for building modern software.

Note

The Go 1 backward compatibility ensures that code written ten years ago still
runs with the latest release. For more details, see the link:
https://go.dev/doc/go1compat
Trivia: Go vs. golang?

Rob Pike proposed the language's name in an email he sent on Sep 25th,
2007:
Subject: Re: prog lang discussion
From: Rob 'Commander' Pike
Date: Tue, Sep 25, 2007 at 3:12 PM
To: Robert Griesemer, Ken Thompson

I had a couple of thoughts on the drive home.

1. name
'go'. you can invent reasons for this name but it has nice properties.
it's short, easy to type. tools: goc, gol, goa. if there's an interactiv
debugger/interpreter it could just be called 'go'. the suffix is .go
...

Disney had already registered the domain "go.com". So, the Go team needed
to register the domain golang.com instead, and the word "golang" was stuck
in the language. To this day, most people call the language "golang". Of
course, the actual name is Go, not golang.

But in a practical sense, the golang keyword makes it easier to find


something related to Go on the web. You can read more about the history of
Go at this link: https://commandcenter.blogspot.com/2017/09/go-ten-years-
and-climbing.html

1.5 What is Go great at?


Go is great for crafting any program, but especially the following:

Client and Server Programs—Go's standard library provides


comprehensive networking support, including HTTP and TCP protocols,
which simplifies the development of client and server programs such as
microservices.
Distributed Network Programs—The concurrency model in Go,
centered around goroutines and channels, is a game-changer for writing
distributed systems. It lets us manage multiple concurrent tasks without
the overhead of traditional threading, making Go a perfect fit for
implementing distributed systems.
Command-line Tools—Go's simplicity and its powerful standard library,
makes it a great choice for developing cross-platform, efficient, and
easy-to-deploy command-line tools.

Although Go is a general-purpose language, its largest user base consists of


backend developers. Let's write a simple program to taste Go before
exploring Go's big features.

1.6 Hello, gophers!


Let's start with a short and sweet program as a first step. This trivial
executable program's goal is to say hello to gophers. As with every Go code,
it's written in a package.
// hello/hello.go
package main #A
import "fmt" #B
func main() {
message := "Hello Gophers !" #C
fmt.Println(message) #D
}

Note

Go programmers are conventionally called "gophers." See:


https://go.dev/blog/gopher.

Running this program is straightforward. You can use the go tool to compile,
link, and run the program. This tool is central to Go and comes with a
compiler, linker, tester, etc.
$ go mod init github.com/username/repository #A
$ go run . #B
Hello Gophers !

Instead of getting bogged down in how this tiny program works, let's
continue the tour. The next chapters extensively explain how to structure,
design, and write Go programs. For instance, Chapter 2 explains how to
create Go modules and packages from scratch.

Note

Go is a simple language and the language mechanics fit in a short document


called Go Spec. Anyone can build a Go compiler by following the rules
outlined in this document. For instance, TinyGo is one of them. Visit the link
to see Go Spec, https://go.dev/ref/spec.

Go is a statically and strongly typed programming language

Go is a statically typed language (i.e., every variable's type is known at


compile time). This enables the compiler to ensure type consistency and
reduces the likelihood of trivial bugs.

Because the memory layout of the types is known at compile time, the
compiler can generate optimized machine code. Additionally, code editors
can do a better job at analyzing the code and help us while editing code.
More importantly, types become the documentation.

Static typing has some potential drawbacks, too. Code is typically more
verbose than dynamically typed languages. Luckily, Go fuses the ease of
usage of dynamic languages in a statically typed language. For instance, in
the example program, Go automatically guesses the message variable's type
without having us provide the type as a string variable.

Note

Go is in a sweet spot between a dynamically typed language like Python and


a statically typed language like C. It draws the best of power from both
worlds. More on this soon.

1.6.1 Compilation and static binary


Go doesn't require an intermediary execution environment such as an
interpreter or a virtual machine. As Figure 1.1 shows, Go compiles code into
efficient (fast) native machine code targeted for major operating systems
(e.g., Linux) and architectures (e.g., AMD64). Go compiles so fast that it
feels as if you're working with an interpreted language like Python.

Figure 1.1 Go compiles code with all necessary dependencies into a single binary.

Go's approach differs from that of interpreted languages. Python, for


example, requires a Python interpreter, while Java requires a virtual machine.
In contrast, a Go binary only requires an operating system to run, making
distributing Go programs straightforward.

The compiler produces a single static binary at the expense of a larger binary
size. This downside dwarfs when compared to the advantages it brings.
Imagine managing a fleet of a thousand Linux servers. All you need to do is
compile the program once, copy it to the target machines, and run it without
any concerns about dependencies.

Note

Chapter 6 dives into how to compile cross-platform binaries (Section 6.3).

Dive deep: How does Go compile so fast?

Unlike Python or Java, Go compiles directly to efficient native machine code,


bypassing an intermediary interpreter. Despite this compilation step,
compiling a Go program is often quicker than most languages. Go's fast
compiler helps us to develop rapidly, and its speed owes to its design. For
more information, visit https://go.dev/talks/2012/splash.article

1.6.2 Go Runtime
Let's explore how Go achieves to run executable programs without any
dependencies. In Go, every executable binary includes Go Runtime (which is
automatically compiled for the target operating system). Figure 1.2 shows
what's typically inside an executable Go program.

Figure 1.2 A statically linked binary that includes everything it needs to run.

An executable binary packs all its dependencies, including Go Runtime that


has the following:

Go scheduler—Orchestrates concurrent functions called goroutines.


Garbage collector—The garbage collector runs in the background and
automatically reclaims memory that is no longer referenced. Go's
garbage collector is also concurrent and scheduled by the Go scheduler.
If you're curious about the garbage collector's internals, visit
https://golang.org/doc/gc-guide.

In Go, you can write code without worrying about freeing up unused
memory.

1.6.3 Pointers
Unlike most other high-level languages, Go allows us to access memory with
pointers directly, giving us explicit control. Unlike C and C++, thanks to Go's
automatic memory management with a garbage collector, pointers are less
dangerous and type-safe.

Thanks to the garbage collector, unlike C, in Go, it's perfectly fine for a
function to return a pointer to one of its local variables. See Figure 1.3 for a
rough illustration.
Figure 1.3 The garbage collector reclaims the memory space occupied by the variable (V) when
there are no pointers (P) left referring to the variable.

There are three functions. The top function calls the middle one, which calls
the bottom one. The middle function receives a pointer to the bottom
function's local variable (V). Since the top function doesn't refer to the
variable, the garbage collector reclaims the variable.

Let's now focus on Go's biggest features: concurrency and type system.

Note

Section 2.2 will further explain how pointers give us the ability to share
variables across our program by referencing their memory addresses, rather
than duplicating their values.

1.7 Concurrency
Go was born out of necessity while the language's creators worked with
highly concurrent servers at Google. Go's basic idea of concurrent
programming is that concurrent functions communicate by sending and
receiving messages. This model draws inspiration from Tony Hoare's 1978
article "Communicating Sequential Processes." In Go terminology:

"Sequential Processes" are goroutines that run a function concurrently.


"Communication" between goroutines is enabled by channels.

Go abstracts classical concurrent programming constructs like threads and


mutexes with goroutines and channels, simplifying concurrent programming.
Let's get an overall feeling of Go's approach to concurrency.

Note

Chapters 2 (Section 2.5), 7, and 8 go into detail for concurrent programming


in Go.

Note

See the Wikipedia link for details about Communicating Sequential


Processes: https://wikipedia.org/wiki/Communicating_sequential_processes

1.7.1 Goroutines
Goroutines are independently running concurrent functions. Figure 1.4 is a
simplified illustration of two goroutines that concurrently run an ordinary
function separately.

Figure 1.4 Goroutines run ordinary functions concurrently. The go statement before a function
spawns a new goroutine that runs the given function.

Concurrency is not an afterthought in Go; it's a fundamental part of the


language and the Go Runtime. The beauty of Go is that it doesn't differentiate
between concurrent or sequential code in terms of syntax. Writing concurrent
code is as straightforward as writing sequential code. For example, say you
have a function that crawls a web page content:
func crawl(url string) {
...
}

You can turn this function into a concurrent one like this:
go crawl("...")
go crawl("...")

This code concurrently runs the crawl function in the background by two
separate goroutines. The go keyword turns a sequential function into a
concurrent one.

In traditional programming languages, thread pools are often used to manage


the high execution cost of running multiple threads. However, in Go, the
story is different. Goroutines are incredibly lightweight, eliminating the need
for a thread pool. This efficiency allows you to run millions of goroutines on
a regular machine, opening up a world of possibilities.

How does it work? Let's dive in.

1.7.2 Go scheduler
An operating system runs executable programs in separate processes. Every
process comprises smaller units called threads that run code on one of the
CPU cores.

Switching between threads (known as context switching) is typically


expensive: the operating system pauses and saves the state of the running
thread, loads the state of the next thread, and runs the next one. This thread
switching overhead can significantly degrade performance in programs with
many threads competing for processor time.

Go's solutions to this problem are:

Abstracting operating system threads with goroutines.


Abstracting the operating system's scheduler with a goroutine scheduler.

As Figure 1.5 shows, the scheduler's job is to distribute goroutines to threads.


There can be millions of goroutines waiting in the scheduler's queue to be
scheduled on a thread.

Figure 1.5 The scheduler multiplexes goroutines onto threads for efficiency. Parallelism occurs at
runtime when multiple CPU cores can run multiple threads in parallel (a nice side effect of
structuring a program to run concurrently).
Context switching between goroutines is tremendously more efficient than
thread context switching because Go's scheduler doesn't have to involve the
operating system kernel (kernel-space calls are an order of magnitudes slower
than user-space calls).

If a goroutine blocks (e.g., due to channel or I/O operations, etc.), the


scheduler parks it, and another goroutine takes place on a free thread, reusing
threads for goroutines. Also, goroutines are cheap and start their life with
2KB of stack memory that can grow or shrink as needed, significantly
reducing the memory resource costs.

For I/O bound work (waiting for input/output operations like network calls to
be completed), Go uses non-blocking I/O to avoid blocking underlying
operating system threads. For instance, numerous goroutines can send
thousands of HTTP requests with a single thread.

Go's approach minimizes the overhead of thread context switching, enabling


Go to integrate concurrency into the language and lead to more efficient
concurrent processing.

Note

Go scheduler's inner mechanics are more complicated than explained here.


Check out the link if you're curious: https://youtu.be/watch?
v=YHRO5WQGh0k

1.7.3 Channels
"Share memory by communicating, don't communicate by sharing
memory."

— Go Proverb

Channels allow goroutines to communicate and synchronize with each other


safely. Think of channels as network cables or Unix pipes between
goroutines. Figure 1.6 illustrates an example of a few goroutines that
communicate through channels.

Figure 1.6 Goroutines that are running concurrently communicate over channels. These
goroutines forward the message to the next goroutine, each doing some computation on the
received message before they send it to the next goroutine.

Here, you see the pipeline pattern where goroutines send messages through a
channel to transfer the ownership of a piece of data to the next goroutine.
While goroutines execute, sending and receiving a message pauses them for a
while so they can synchronize.

While using classical concurrency primitives like mutexes (which Go


supports) is fine for serializing and protecting concurrent access to a shared
resource (e.g., a counter or a cache), the idiomatic way is to use channels
when you want goroutines to communicate (passing ownership of a piece of
data, distributing tasks, communicating results).

When structured correctly, this message-passing approach simplifies


concurrent programming by making the data flow explicit and reducing the
likelihood of concurrency-related bugs. The book dives into how to structure
idiomatic and testable concurrent programs correctly, starting from Chapter 7
(also see Section 2.5 for an intro).

1.7.4 Wrap up
"If all you have is a hammer, everything looks like a nail."

—Abraham Maslow's law of the instrument.

Many newcomers to the Go programming language often fall into the trap of
applying Go's concurrency features to every problem they encounter. This is
mainly because Go makes it relatively easy to turn sequential programs into
concurrent ones.

However, this approach is rarely the best one.

While Go's concurrency model makes it easier to work with concurrent code,
humans are naturally wired to understand sequential execution better.
Therefore, it's important to resist the temptation of using concurrency unless
it's necessary for solving the problem at hand.

1.8 Type system


"If you could do Java over again, what would you change?" "I'd leave
out classes," he replied. ...The real problem wasn't classes per se but
rather ... inheritance.

— James Gosling (Java's inventor)

The next standout feature of Go is its simple and effective type system.

Unlike other popular programming languages that rely heavily on classes and
inheritance, Go implements a lean version of object-oriented programming.
Go's type system is flat, meaning that there are no type hierarchies, classes, or
inheritance. Polymorphism is only possible via interfaces. Go favors
composition over inheritance.

While it is possible to imitate similar flat types in other languages by


avoiding inheritance and using only interfaces to achieve polymorphism, Go
makes it a requirement. This approach prevents unintentional damage caused
by overusing type hierarchies.

Now, let's take a high-level overview of embedding and polymorphism in Go.


It's okay if you don't understand the examples yet, as the later chapter will
delve into these concepts and explain them in detail. Nonetheless, having a
rough understanding is sufficient for now.

1.8.1 Embedding instead of inheritance


Go's type system eschews classical inheritance in favor of a flat structure.

Instead, Go has struct embedding, allowing one struct type to include


another's data and methods, akin to composition. However, unlike
inheritance, embedding doesn't establish a parent-child relationship; the types
remain distinct and aren't interchangeable.

Note

Think of a struct type similar to a lightweight class.

Figure 1.7 illustrates the differences between inheritance and embedding.

Figure 1.7 While inheritance creates a type hierarchy, embedding does not. In inheritance, you
can pass parent (square) and child (circle) types interchangeably to a function that expects only
the parent type. With embedding, the function can only work with the specified type. Embedding
does not form a type hierarchy. Embedding simply makes one type's methods and data part of
another type.

The distinction is crucial: when a struct embeds another, it doesn't inherit


from it. This concept helps maintain clear boundaries between types and can
prevent some of the common pitfalls of inheritance, like tight coupling and
difficulty in understanding code hierarchies. It's part of what gives Go its
characteristic simplicity and power in design.
Programmers new to Go are often surprised when they see they can't use a
struct type that embeds another in place of the embedding struct type. They
are surprised because they mistakenly think that embedding is inheritance,
which Go does not support.

Note

Chapter 2 (Section 2.4.1) explains struct types, and Chapter 9 (Section 9.3.1)
explores embedding in more detail.

1.8.2 Implicit interfaces


Go interfaces blend the flexibility of dynamically and statically typed
languages. You can pass types to functions based on their methods (duck
typing). At the same time, Go brings static typing benefits; like Java, Go
checks at compile time that the types match the interface's methods. Go's
approach provides both flexibility and reliability in your code.

Go can achieve this flexibility because interfaces are implicitly satisfied.


Types do not have to explicitly mention that they implement an interface. If a
type implements all the methods of an interface, you can use the type
wherever that interface is expected (duck typing: if it quacks like a duck and
walks like a duck, then it should be a duck).

Note

Go's implicit interfaces empower you to craft code that's easy to manage and
adapt.

Figure 1.8 illustrates an example usage of Go's implicit interfaces. Say, you
have an interface called runner with a run method, the square and circle
types, each with a run method (behavior), and lastly, a function that expects
the runner interface.

Figure 1.8 The function expects a type that implements the runner interface (any type with a
run() method). You can interchangeably pass either of these types to the function because each
has a run() method and implicitly satisfies runner.
Notice that these types say nothing about the runner interface. Each
implements only the run method, which allows you to pass any of them to the
process function. If you pass a type without the run method to the function,
the code won't compile.

In practice, Go's implicit interfaces offer an unmatched level of simplicity,


flexibility, and reliability in program design. By decoupling the concrete
implementations from their behaviors, Go encourages a more modular and
scalable code structure.

You don't have to design interfaces upfront. Go's approach empowers you to
write code that is easy to maintain and adaptable to future changes without
requiring extensive refactoring.

Note

Chapter 2 dives into methods and interfaces (Sections 2.4.2 and 2.4.3). Most
of this book is about the idiomatic usage of methods and interfaces.

Note

Go also has limited support for generic type parameters. See the link for more
information, https://go.dev/doc/tutorial/generics. Section 2.4.4 also explains
generics.

Decoupling and testing with implicit interfaces

Let's briefly explore how Go's implicit interfaces boost the testability of code.

Mithril is an imaginary payment processor, and you want to test code that
uses Mithril's API. As Figure 1.9 shows, when you run the test, the code
under the test charges users for money! How can you test this code without
sending requests to Mihtril's live servers?

Figure 1.9 This expensive test runs code that invokes the charge method of Mithril's API and
contacts live servers. It's not the best way of testing.

The problem is Mithril's API doesn't offer interfaces, which poses a challenge
for testing. This is where Go's implicit interfaces shine. Instead of costly tests
against Mithril's servers, you can decouple your code by declaring a tiny
interface with a subset of Mithril's API methods.

Here's the recipe (see also Figure 1.10):

1. Declare an interface (i.e., charger) with a single charge method.


2. Create a test-only fake payment processor type with a charge method.
3. Change the code to accept the charger interface.
4. Pass this fake type to the code while testing.

Figure 1.10 Testing the code with a fake payment provider. The code no longer uses Mithril's API
methods. Instead, it uses the fake payment provider.

The code no longer depends on Mithril's API; instead, it accepts the charger
interface. This approach enables you to pass any type with a charge method
to the code (including the fake payment processor while testing or the actual
Mithril's API). Mithril's absence of an interface was never an obstacle for
testing. In Go, you can always defer declaring an interface until needed,
making your code straightforward to evolve and also testable.

This is one of the prime examples of Go's practicality. Go allows you to craft
testable code without designing types upfront, effectively allowing you to
evolve your code with confidence, even when third-party interfaces aren't
available. This technique, along with others you'll learn in this book,
showcases how Go is engineered for building solid software.

Note

Chapter 6 and Chapter 11 (Section 11.5) dive deeper into testing with
interfaces.

1.9 Standard Library


Go comes with a rich set of packages called the standard library. These
packages include functionality, from simple tasks like string manipulation to
running HTTP servers. By reusing the functionality offered by the standard
library, you can develop your programs rapidly.

For instance, here is an example of running an HTTP server using the


standard library:
package main
import "net/http"
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello, gophers!"))
}
http.ListenAndServe("localhost:8080", http.HandlerFunc(handler))
}

This program listens on port 8080 of localhost. Once it receives an HTTP


request, the server sends a "hello, gophers!" message to the client. Thanks to
concurrently serving requests with goroutines, even this basic server can
handle tens of thousands of requests per second.

Note
Chapter 9 explains how to structure and write HTTP servers in detail.

Besides the standard library, Go has a vibrant and mature ecosystem of


mature third-party packages. It's also straightforward to download and use
these packages using Go's built-in module system. Yet, it's wise to use the
standard library if it offers the packages you need.

The standard library is a tribute to reliability, having undergone rigorous


testing and tight integration with the Go runtime. This often leads to more
robust and efficient code. Moreover, most Go developers are familiar with
the standard library code, which means it's easier for everyone to understand
each other's code and work together effectively.

Note

You can see the standard library packages at the link: https://pkg.go.dev/std.

This book uses the standard library for all the examples in the book. For
example, Chapter 3 introduces the testing package for automated testing.
Chapter 5 uses the flag package for command-line flags. Chapter 8 uses the
http package for sending requests, and so on.

1.10 Tooling
Another reason Go is so successful and popular is its great built-in tooling
support. Go tools play a critical role in a gopher's workflow, from
automatically managing dependencies and formatting code to compiling. You
can use all the tools through a single go command.

For example:
$ go test .
PASS

Go prioritizes tests as first-class, and with the go test tool, you can
effortlessly run tests, benchmark, and profile your code to identify areas
where it's spending the most time. Or, you can also use the go fmt tool to
format your code automatically.
From this:
package main;import "fmt"
func main() { fmt.Println("hello, gophers!" )}
To this:
package main

import "fmt"

func main() {
fmt.Println("hello, gophers!")
}

The formatting tool is tremendously helpful for keeping code consistent


across every Go project. No more tabs vs. space wars. Here's a list of a few
more tools:

go build: Compiles Go code.


go run: Compiles and runs Go code.
go get: Downloads third-party packages and add them to your project's
Go module so that you can import them into your program.
go vet: Finds potential issues in Go code to improve code quality.
go doc: Displays documentation for packages.
go generate: Generates Go code for common tasks.

These are just a few examples of the many built-in tools in Go. Thanks to
Go's tooling, you can focus on coding. Visit the link for other Go tools:
https://pkg.go.dev/cmd/go.

1.11 Downloading the book's source code


If you wish to follow along with the examples provided in this book (which I
strongly recommend), you may want to access the corresponding source
code. To make things easier for you, the source code for examples is
available from two different sources.

https://github.com/inancgumus/gobyexample
https://www.manning.com/books/go-by-example

Before getting started, you also might want to install the latest version of Go:
https://go.dev/doc/install

This chapter has dissected why Go exists and the problems it's crafted to
solve, cutting through the trivia and diving into the heart of what makes Go
stand out—its simplicity, pragmatism, and efficiency. With an introduction to
Go's strengths, you've begun the journey to understand how Go makes it
easier to construct reliable and performant software.

As the first chapter concludes, I hope you're beginning to recognize the


reasons to delve further into the world of Go and continue reading this book.
This book is structured to help you develop the right mindset for utilizing Go
language's idioms and mechanics effectively. It will serve as your guide in
crafting idiomatic, maintainable, and testable code in Go.

1.12 Summary
This book will be your guide to writing idiomatic and testable code.
Learning through examples is an effective way to learn a new
technology.
Go is a simple and effective programming language.
Go fuses the best sides of dynamically and statically typed languages.
Go code is written in packages and compiled into efficient native
machine code.
The compiler produces a single static binary, making deployment
straightforward.
Every executable comes with Go Runtime, including a scheduler for
concurrent execution and a garbage collector to automatically reclaim
unused memory.
Go doesn't hide the cost of doing something and has pointers to use
memory directly. Pointers enable us to share values without copying
them. The garbage collector can automatically free unused memory
referred to by the pointers.
Automatic memory management allows returning pointers from
functions.
Concurrency is built-in in the Go language. There is no difference
between writing sequential and concurrent code. It is straightforward to
turn the prior to the latter.
The Go scheduler abstracts the operating system scheduler and threads.
Goroutines are independently running concurrent functions.
Channels allow goroutines to communicate and synchronize with each
other.
Go's type system is flat and does not support classical inheritance.
Embedding allows a type to be embedded into a struct type.
Embedded and embedded types are different and don't form a type
hierarchy.
Interfaces are explicitly satisfied, decoupling implementations from
interfaces.
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:

Packages named main are for building executables and cannot be


imported.
Packages named anything but main can be imported from other
packages.

Definition

A package is a set of Go source code files in the same directory.

We'll have two packages for our example program: main and book. See
Figure 2.1.

Figure 2.1 The main package imports the book package to use its functionalities.

We'll start with the importable book package. The main package we'll write
after will import the book package and call the Title function to write this
book's title to the console.

2.1.2 Importable packages


As the next listing shows, the book package declares two functions: Title
and subtitle. They don't take an input parameter but return a string. The
package statement makes the book.go file a part of the book package. There
can be many files inside a package.

Listing 2.1 The book package (book/book.go)

// Package book offers information about the Go by Example book.


package book #A

// Title returns the title of this book.


func Title() string { #B
return "Go by Example: "+ subtitle()
}

func subtitle() string { #C


return "Programmer's Guide to Idiomatic and Testable Code"
}

We've created an importable package named book. Let's talk about exporting.

Note

We can export a package's items by capitalizing their first letter to make them
public.

Go relies on packages as its sole isolation mechanism.

The code in the same package can access everything within their package.
However, other packages can only access the items a package exports. For
instance, the main package can import the book package and call Title
because it's exported, but not subtitle. Still, Title can access subtitle
because they are within the same book package.

Title as a function name is idiomatic, while GetTitle, GetBookTitle, or


BookTitle are not. Is the book itself getting the title? Of course not. Prefixing
Title with "Get" adds unnecessary noise. Omitting "Get" is also crucial for
readability when calling Title from other packages: book.Title(), precisely
meaning the book's title. We also don't want to repeat (stutter) the package
name, as book.BookTitle(). Again, unnecessary noise.

Note
Every source file in a package directory must declare the same package.
Idiomatic package names are nouns, descriptive yet concise, like book. They
are lowercase and lack underscores or mixed caps. Ideal names convey what
a package offers.

Dive deep: Test packages

Tests can declare a test package, like book_test, in the same directory with
the book package because they're only included while testing—we'll cover
testing later.

2.1.3 Package main


In the next listing, the main package imports the book package and calls
Title. Then, main passes the returned title to the fmt package's Println
function to print the title.

Listing 2.2 Implementing package main (hello.go)

package main

import (
"fmt"
"github.com/inancgumus/gobyexample/book"
)

func main() {
fmt.Println(book.Title())
}

While importing packages, the last segment—book—in the import path is the
package's name. Go Standard Library packages, like fmt, don't need a full
path.

Note

Defining a package as main signals to the Go toolchain that it contains the


program's entry point. The main package doesn't automatically make the
package executable—the main function within the main package signals that
the package should be built as an executable binary and allows designating
the main function as the program's entry point.

Running the program

Now that we have all the parts of our program, it's time to run it. We can use
the go run command to compile and run our executable program. The main
function is an executable program's entry point and it'll be called when we
run our program.
$ go run .
go: go.mod file not found in current directory or any parent directory...

We ran our program but received an error. Let's fix this error by initializing a
module.

2.1.4 Modules
For every new project, we must initialize a module to manage dependencies.
As shown in Figure 2.2, conceptually, a module is a collection of packages
with a unique name, often a URL, to ensure uniqueness. In practice, a module
is simply a file named go.mod in a project's root. It's like package.json in
Node.js or requirements.txt in Python.

Figure 2.2 A module is a collection of packages.

Note

While we can use non-URL module names, this might lead to difficulties in
locating and downloading the module. Using a URL ensures that our modules
can be uniquely located.

Let's go to our project's directory and initialize a module with the following
command.
$ go mod init github.com/inancgumus/gobyexample #A

This command creates a go.mod file in the current directory with the
following content.
module github.com/inancgumus/gobyexample #A
go 1.22 #B

This file can include the module dependencies of our module. For now, we
don't depend on other modules. We'll see how to download and use other
modules in later chapters.

Note

Throughout the book, we'll use the same module we just initialized. Visit the
link to learn more about Go modules: https://go.dev/blog/using-go-modules.

2.1.5 Building and running


Now that we initialized the module, we can finally compile and run our
program.
$ go run . #A

Go by Example: Programmers Guide to Idiomatic and Testable Code

The run command is excellent for prototyping and throws away the
executable binary after the program stops. The build command lets us keep
the executable:
$ go build -o hello #A

$ hello #B
Go by Example: Programmers Guide to Idiomatic and Testable Code

Deployment of this binary is simple since it's self-sufficient without any


external dependencies—build, copy, and run it on a target machine. Still, we
must recompile the code for target platforms. Thankfully, Go can compile to
major operating systems, including Linux, Windows, and macOS, and a wide
range of architectures, including AMD64, ARM, MIPS, WASM, and more.
We'll look at how to cross-compile in Chapter 6 (Section 6.3).

2.1.6 Exercises

Create a new directory and initialize a Go module.


Create an importable package and import it from the main package.
Your package should have exported and unexported functions that you
can call from main.
Compile and run your program using go build and go run.

2.1.7 Wrap up
The main package's main function is an executable program's entry
point.
Packages named other than main can be imported by other packages.
Packages can only access the exported items of other packages.
Exporting is done by capitalizing the first letter of an item inside a
package.
The go mod init command initializes a Go module.
The go run command runs an executable program and throws away the
binary.
The go build command compiles packages.
Go Runtime is included with every executable Go program and contains
a Go scheduler to orchestrate goroutines and a garbage collector to
recycle memory.

It's time to focus on Go's distinctive features so we can be ready for the next
chapters. We'll start with pointers, crucial for being effective at Go. Then,
we'll dive into collection types like arrays and slices, object-oriented
programming, concurrency, and lastly, error handling.

2.2 Pointers
Every variable stores a value at a unique spot in computer memory tagged
with a numeric address (typically depicted as hexadecimal). While some of
these variables store raw values, others store memory addresses of other
variables. A pointer is a variable that stores another variable's memory
address. See Figure 2.3 to see how variables are stored in memory.

Figure 2.3 A variable stores a value at a memory location tagged with an address. The numbers
below are simplified memory addresses of each variable shown.

We can declare these variables like this:


counter := 42 #A
ptr := &counter #B

The counter variable stores an integer value of 42 in the memory spot tagged
with an address of 0x1. While the ptr variable is a pointer at address 0x3.
This pointer stores the first variable's memory address of 0x1—it's pointing to
counter. Keep in mind that these memory addresses are for illustrative
purposes. They will be different at runtime.

For those from programming backgrounds without pointers, think of a pointer


as the book index on the back cover. It tells us where the page is rather than
the page's content. Otherwise, the book index would copy the page's content
instead of referring to it.
index (pointer) page content (data)

Look at page 42 for pointers -> Pointers are ...

Or a URL to a web page is a pointer to that page. The URL doesn't contain
the page content, but it points to where we can find the information. It's a
rough analogy but it might help.
url (pointer) web page content (data)

http://foo.com/abc -> lorem ipsum dolor sit amet...


If you're already familiar with pointers from languages like C or C++, Go's
pointers will feel similar, but Go disallows pointer arithmetic, and it uses a
garbage collector. For instance, in C/C++, returning a pointer to a local
variable might be a bug that can lead to surprising behavior. In Go, the
garbage collector keeps track of pointers and the values they reference, so it's
safe to return a pointer from a function; the memory won't be reclaimed until
no references are left. We'll cover these differences in detail throughout the
book.

2.2.1 Variables and pointers

Let's look at variables and pointers in more detail.

The following declares an int (integer) variable named counter without an


initial value.
var counter int

Note

Go is statically typed, and we cannot change variable types after declaring


them.

Let's also declare another variable. This time, a pointer variable. Its name is
ptr, and type is *int (a pointer to an int variable). Its value is nil (doesn't
point to a memory address).
var ptr *int

Note

Pointers are type-safe. For instance, we can only assign an int variable's
memory address to the pointer variable ptr. This provides type safety and
makes security breaches less likely.

Lastly, let's declare a variable that uses the Duration type from the time
package.
import "time"
...
var responseTime time.Duration

In Go, every variable is always initialized to a zero value. This reduces the
chances of certain memory corruption bugs that can crash or open a program
to attacks.
fmt.Println(counter) // prints 0
fmt.Println(ptr) // prints nil
fmt.Println(responseTime) // prints 0s #A

Note

Every variable declared without an initial value gets a zero value. For
numbers, the zero value is 0; for strings, it's an empty string—""; for
booleans, it's false; for pointers types, it's nil.

Now, let's start over and look into type inference. This time, we'll declare the
variable counter using the short declaration syntax and give our variable an
initial value.
counter := 42 // initialized with 42
fmt.Println(counter) // prints 42

The compiler infers the counter's type as int because we initialize the
variable with an int constant of 42. Since Go is type-safe, we can now assign
only an int value to counter.
counter = 42 // ok: assigning an int value

But the following won't work and result in a compile-time error.


counter = int64(84) // error: 84 is int64, not int

counter = 3.14 // error: 3.14 is float64 #A


counter = int(3.14) // ok: counter is 3

We needed to convert 3.14 to an int value of 3, losing the fractional part.


Now that we looked at variables, let's dive into pointers and address
operators.
Note

Remember not to confuse := with =. The former is a short declaration; the


latter is an assignment. Here is more information:
https://stackoverflow.com/a/45654233.

2.2.2 Address operators


As discussed, a pointer is a variable that stores the memory address of
another variable. Figure 2.4 shows two variables: counter (an int) and ptr
(an *int—a pointer to an int variable). The latter is a pointer and stores the
counter variable's memory address.

Figure 2.4 Declaring a pointer that references a variable's memory address and dereferencing the
pointer to find the value inside that variable via the pointer.

Similar to C, we use the following operators to utilize pointers:

The ampersand "&" before a variable returns the variable's memory


address.
The asterisk "*" before a pointer returns a variable's value pointed by the
pointer.

Using these operators, we fetch and put the counter's memory address (0x1)
into the pointer variable, ptr. Then, we indirectly fetch the counter's value
(42) through ptr.

Let's look into this in practice. We'll first declare a nil pointer variable. Like
NULL or null in other languages, nil means a pointer that points nowhere. It's
the zero value for pointers.
var ptr *int // this variable's type is *int (a pointer to int)
fmt.Println(ptr == nil) // prints true (doesn't point to an address)

Note

We can compare only pointers to nil. Types like slices, maps, interfaces,
channels, etc. implicitly involve pointers and we can compare them to nil.
More on this later.

Like the figure, let's declare counter, take, and store its address in ptr.
counter := 42 #A
ptr = &counter #B
fmt.Println(ptr) // prints 0x1 (assuming that's the counter's address

Since ptr points to counter, we can fetch counter's value by dereferencing


ptr using *.

fmt.Println(*ptr) // prints 42 (counter's value)

Note

Don't confuse dereferencing with a pointer type. *ptr is dereferencing since


the star is before a pointer, whereas *int is a pointer type since the star
comes before a type.

We dereferenced a pointer that points to a memory address. If we dereference


a nil pointer, our program will panic (crash). That's why we should be
careful while working with pointers.
ptr = nil // now, the pointer doesn't point anywhere

fmt.Println(*ptr) // panics (crashes in runtime)

To sum up, & gets a variable's memory address, and * gets a variable's value
through a pointer. Now, let's dive into pass-by-value to see where pointers
might be helpful.

Dive deep: Unsafe

Because Go has a garbage collector, it doesn't allow pointer arithmetic. It's a


design choice in favor of a more secure approach. Still, using the unsafe
package, we can do pointer arithmetic. Although we rarely use unsafe since
it defeats the purpose of the type system and safety, it might become useful.
This article discusses using CGO and unsafe for talking to C code:
https://go.dev/blog/cgo.

2.2.3 Pass by value mechanics


Go is pass-by-value. Passing a variable as an argument to a function copies
that variable's value into a local variable within the function. Any changes to
that variable will stay local to the function and won't be visible outside of it.
Let's look at the next listing for an example.

Listing 2.3 Passing a pointer to a function (ptr/ptr.go)

package main

import "fmt"

func main() {
counter := 42

incrVal(counter) #A
fmt.Println(counter) // 42

incrPtr(&counter) #B
fmt.Println(counter) // 43
}

func incrVal(c int) {


c++
}

func incrPtr(c *int) {


*c++ #C
}

We have three functions: main, incrVal, and incrPtr. Inside main, we


declare a variable named counter with a value of 42. Then, we try to
increment the variable with the incrVal and incrPtr functions. While the
first one fails to do so, yet the second one succeeds.
See Figure 2.5 to find out why.

Figure 2.5 Pointers enable us to mutate original values without copying them. Numbers below are
the memory addresses of each variable.

The short answer is incrVal takes a value type—int—while incrPtr takes a


pointer type—*int, which is a pointer to an int value. Here's the long
answer.

Calling incrVal copies counter's value to its local variable c of type


int. Mutating c doesn't modify the original: counter remains 42 while
the local one becomes 43.
Calling incrPtr copies counter's address to c of type *int. It finds the
counter's address and updates the counter's value to 43.

In summary, after passing them pointers, functions can update the original
value. The key to remember here is that pointers are copied, too. They just
point to the same original variable.

Note

There can be many pointers pointing to the same value. For instance, we
could declare ptr2 := &counter and it would point to the counter variable
as ptr does.

Dive deep: stack and heap memory


In Go, functions can return a pointer to a function-local variable. For
instance:
func newInt() *int {
n := 42
return &n #A
}

The newInt function returns a pointer to its local int variable n. Although we
rarely return a pointer to basic types like an int, returning pointers from
functions is fine. For instance, a function can print 42 via the returned pointer
after calling newString:
func main() {
m := newInt()
fmt.Println(*m) // prints 42
}

Once newInt returns a pointer to its local variable, n typically moves from the
stack memory to the heap memory ("escapes to heap"). So, while local
variables like n usually reside in the stack memory, returning a pointer might
allocate the variable on the heap memory (but it's not a guarantee, the
compiler might decide otherwise). The main function can access n's value
because the heap memory is shared between functions (unlike the stack
memory).

Unlike stack memory, heap memory can become fragmented over time and
filled with garbage values that are no longer needed. This is where Go's
garbage collector steps in. It automatically watches heap memory and
periodically reclaims unreferenced variables.

We don't need to concern ourselves with these details as Go automatically


handles memory management. However, understanding this can help for a
deeper understanding of Go.

2.2.4 Exercises
Declare a few variables. Try assigning different types of values to every
variable you create and observe the compiler errors. Increment integer
variables. Pass and mutate these variables in a function and check if
your changes are visible outside.
Declare a pointer variable to one of these variables and pass them to
functions. Mutate the variables through the pointers and observe your
changes from the caller.

Tip

You can find the basic types at the link: https://go.dev/ref/spec#Types

2.2.5 Wrap up
Pointers are so helpful that many languages implicitly use them. Take Java,
for instance: every object is essentially a pointer. But Go, like C, is candid
about pointers, making them explicit, leaving the decision of using a pointer
to us for precise control over memory. We'll later dive into when to use a
pointer and when not to. Let's wrap up.

Variables are strongly typed, always initialized, and stored in a unique


memory spot.
Pointers are type-safe and store the memory addresses of other variables.
Go is pass-by-value, and values are always copied when passing them
around.
Pointers let us work with original values without copying them.

Dive deep: Some types implicitly involve pointers

Although we say that the handling of pointers in Go is explicit, certain types


implicitly involve pointers because of necessity or to make things easier. For
instance, slices (dynamic arrays) have a pointer to their underlying arrays.
Maps are pointers to complex data structures in Go Runtime. Similarly,
interfaces, function values, and channels use pointers.

We'll explore these topics in this chapter and continue throughout the book.

2.3 Collections
Go has three built-in collection types: arrays, slices, and maps.

Arrays are fixed-length collections of elements of the same type.


Slices are like dynamic arrays that can expand and shrink.
Maps are key-value pairs to access elements through their keys in
constant time.

2.3.1 Arrays
Say we want to store RGB (red, green, and blue) colors in an array:
rgb := [3]byte{41, 190, 176} #A

Figure 2.6 illustrates the rgb array and the operations we can use on it.

Figure 2.6 A byte array with three consecutive byte elements laid out in memory. While the built-
in len function returns the array's length, 0-based indexing returns an array element at that
index (e.g., rgb[0] returns the first element).

Note

The byte type is an alias for the uint8 type (an unsigned 8-bit integer). We
can also declare arrays of any length and type, such as [10]string,
[16]bool, etc.

This array's type is [3]byte (an array of three bytes). An array's length and
element type determine its type (which cannot be changed without
recompiling the program).

It might be surprising, but arrays with different lengths have different types:
rgb = [4]byte{214, 65, 79, 255} #A
Passing arrays to functions

Now, say we want to invert the colors of an 8K image (7680 x 4320 pixels).
Since each pixel has RGB colors, we declare an array with ~100 million
bytes (7680 * 4320 * 3). Then, we pass the array to a function that loops over
and mutates each array element.

Listing 2.4 Passing arrays to functions (arrays1/array.go)

package main

const resolution8K = 7_680 * 4_320 * 3 #A

func main() {
selfie := [resolution8K]byte{ /* ..color data.. */ } #B
invertColors(selfie)
}

func invertColors(colors [resolution8K]byte) { #C


for i := range colors { #D
colors[i] = 255 - colors[i] #E
}
}

We use a constant (for readability) to declare an array that occupies 100


megabytes of memory space. The invertColors function takes the array and
loops over each element. The index variable i gets updated from 0 to the
array's length - 1 (len(colors)-1). Inside the loop, we mutate each array
element to invert the colors. So far, so good. However...

Passing pointers to functions

Passing the array to invertColors copies ~100 megabytes of data from one
spot in memory to another, which is inefficient. As Figure 2.7 shows, the
function gets a copy of the array.

Figure 2.7 Passing an array to a function copies the entire array.


Instead, we can use pointers for efficiency. As the next listing shows, we
update invertColors to take a pointer. Then, we pass the pointer of our array
to the function.

Listing 2.5 Passing arrays to functions with pointers (arrays2/array.go)

package main

const resolution8K = 7_680 * 4_320 * 3

func main() {
selfie := [resolution8K]byte{ /* pixel data */ }
invertColors(&selfie) #A
}

func invertColors(colors *[resolution8K]byte) { #B


for i := range colors {
colors[i] = 255 - colors[i] #C
}
}

Note

Calling this function only copies the array's pointer, not the array's entire
elements.

As Figure 2.8 shows, passing the array's pointer to the function only copies 8
bytes (pointers are always 8 bytes on a 64-bit machine) instead of the entire
array. Moreover, the function can mutate the original array's elements via the
pointer without copying.

This approach is much more efficient than passing and copying a large array.

Figure 2.8 Passing the array's pointer to the function only copies 8 bytes.
This pointer points to the array's memory address. We could also point to the
individual array elements with separate pointers (e.g., &selfie[1] points to
the second element), but we don't need it here. However, we rarely use
arrays; slices are more useful in practice.

Exercises

Note

Imagine what the data looks like for these exercises; it doesn't have to be
real-world data.

Write a function to calculate total sign-ups from a daily user counts


array.
Pass a pointer to a function to update network response speeds array.

Wrap up

Arrays (i.e., [Length]ElementType) are fixed-length collections of


elements.
Array's length and element type fuses together to determine its type.
len() returns the array's length.
Passing arrays around copies the elements in the array to a new array.
Passing large arrays around by pointers can be more efficient.

Dive deep: Arrays

Since their lengths and element types are fixed, arrays always occupy the
same memory space. We should recompile our programs if we want an array
to hold more (or less) elements. Arrays would waste memory space if we
Other documents randomly have
different content
The door opened at that moment and admitted an elderly
obsequious man in black, with a big parchment folded under his arm;
and behind him came Baron Blumenstrauss, Lady Wyse, Mr. Cato,
and a lean brown man with a tuft on his chin, whom Sir Peter had
seen there once before. This man smiled at Sir Peter drily. The
obsequious man said good-bye, and shook hands with the Prince.
‘It’s all right, your Royal Highness; signed, sealed, delivered, and
stamped.’
‘Quite sound in law, is it?’ said the Prince.
‘Inter fifos,’ nodded the Baron; ‘sount as a pell.’
The obsequious gentleman hurried out.
‘Fonny man!’ said the Baron, patting the Prince on the shoulder, and
smiling at Sir Peter; ‘he gif his broperty all away, effery penny.’
‘It’s generous, dear Prince,’ said the Biologist, ‘but is it wise? Even
out there, no doubt, one has expenses.’
‘Oh! I sha’n’t want any money,’ said the Prince.
‘They have no pockets, you know,’ said Lady Wyse.
Whereupon the Baron, who was not initiated, adjusted his glasses
and looked at her with great attention.
‘Remember King Lear,’ said the Biologist. ‘He divided his property in
two’....
‘Seely fellow!’ said the Baron.
‘And his daughters were both ungrateful.’
‘Natürlich!’ said the Baron. ‘He trowed away de chief ting he haf; he
gif de broperty widout de power. If I difide my corner in Brazilians into
two corners for de boys, do you tink Max and Choel loff me very
moch?’
‘You would find some Cordelia, I am sure, dear Baron.’
‘Nod widout monny,’ said the Baron.
‘There’s no Cordelia in this case,’ said Lady Wyse; ‘I’m Goneril and
the other lady all in one.’
‘Really?’ The Biologist was all smiles and proffered hands. ‘I
congratulate you. The Prince couldn’t have disposed of his fortune
better, I’m sure.’
‘Ah! that depends how people treat us.’
‘Dere is gondition,’ said the Baron, looking at his watch.
‘May one inquire, dear Prince, what the condition is?’
‘Oh! it’s a mere nothing.’
‘Lady Wyse publish his “Memoirs,”’ said the Baron.
The Biologist turned pale.
‘That reminds me,’ said the American; ‘I mustn’t leave those papers
litterin’ about. I forgot to lock them up.’
‘Goot-bye,’ said the Baron. ‘I haf beesness encagement.’ He
followed the American out at the door.
‘Of course!’ said the Biologist, brightening. ‘“Memoirs of a
Statesman”—anecdotes of the great people you have met. Who is
the American-looking man?’
‘Oh! that’s Mr. Bone, one of my collaborators. Mr. Cato and Lady
Wyse are the others; between us, you see, we cover the whole
ground. I met Mr. Bone in Borneo. In fact, he was ... he was my
proprietor. I’m going to leave the history of my life as a legacy and a
lesson to the English Nation.’
‘You’ll have to go over to Borneo with the Prince, Sir Peter,’ said
Lady Wyse: ‘you’ll be much more comfortable up one of his trees
than you will be in England.’
The question had been debated many and many a time between
them. Mr. Cato, as always, was for candour; he felt that Dwala was
in a false position; he thought the secret should be published at
once, and guaranteed the enthusiastic interest of the nation. Mr.
Bone, for other reasons, agreed with him as to immediate
publication; he thought there was money in it. Lady Wyse was all for
caution; she lacked the business instinct of the American, and the
optimism of Mr. Cato; she doubted the enthusiasm of the public; she
thought it was running into unnecessary danger to publish the secret
before the Prince was out of the country. It had therefore been
agreed that she should publish it as soon as he was safe in the great
forest again. She was ready to incur any danger herself; she was
tired of life; and she did not in the least mind what happened to the
Biologist.
The Biologist saw ruin impending. Savage, reckless hatred welled in
his breast as he looked at this great creature, fatally sick, but
rejoicing in a present intensity of life and vigour. He groped about for
something sharp and venomous to pierce him with; to make him fall
beside him into the valley of despair. He walked up to Dwala, hissing
like a serpent in his face.
‘You have come to Man as an apostle, bringing us a new message of
Civilisation.’
Dwala nodded, rather proudly.
‘Do you know what Man has given to you in return? What Man
always gives to such animals? What any scientist could have told
you you were bound to get in coming?... Consumption.... Phthisis
pulmonalis.... Death!... Going back while you’re young and strong to
your wild life in the forest! Pish! You won’t live the month out. I knew
it that night. You’re a dying beast.’
Alas! why had Lady Wyse never told him? He had never thought of
that. Life hummed and bubbled through his veins. He knew nothing
of sickness and death. He had always been alive. The world had
been faint at times; but that was the world, not he. A stiffening horror
ran through him; he felt his skin moving against his clothes. Then his
mind ran rapidly through all the series of events—the growth to the
full knowledge of Man, the labouring hope of a joke, the change, the
revelation, the submission to an overwhelming truth, the rejoicing
millions.... Then suddenly this discovery of an unsuspected
vengeance-for-benefit which had been stealing slowly and surely
from the first in his steps, to spring at last on his back in the moment
of fruition.
It was too funny; the surprise of the inevitable overcame him; it was
a Joke which suddenly leaped up embracing the whole life of a
created being, and the destiny of a nation—of humanity itself.
Dwala laughed. For the last time he laughed. A laugh to which his
others were childish crowings; a laugh which flung horror on to the
walls and into the darkened air, and spread a sudden dismay of
things worse than death throughout the land. Men stopped in their
work and in their talk and their lips grew pale without a cause; some
goodness had gone out of Providence; some terror had been added
to Fate. From the fire of that dismay the Biologist emerged a
withered and broken man; Mr. Cato never flinched, his sheer
goodness protected him; Lady Wyse broke into tears. She, too, was
unscathed. No human canon of ethics has been invented by which
she could be called good; she was a breaker of laws, an enemy of
her kind. But in the place of ‘goodness’ she had a greatness which
set her above the need of it.
When the paroxysm of laughter was ended, Dwala staggered and
sank into a chair, and they saw him hanging from it with the blood
streaming out of his mouth.
At once they were in the world of definite, manageable facts again.
The Biologist became the attentive practitioner, Lady Wyse the
understanding woman, Mr. Cato the bewildered layman, busily doing
unnecessary things, ringing the bell, calling for brandy, hurrying out
into the hall to see why they were so long. Huxtable and the
American came running down the stairs, and Dwala was carried to
his room and put to bed.
XXXV
While all the household radiated about Dwala’s sick-bed, and there
was no attention for any other thing, the Biologist ran swiftly up the
stairs, guided by a superhuman instinct of despair, straight to the
American’s room. He was going to seize the ‘Memoirs’ and burn
them. Dwala was dying; no new authentic copy could be produced
again. In the doorway he saw that his instincts had guided him
aright. American things greeted his eyes—an American hat on the
chest of drawers, American corn-cob pipes on the mantelpiece. But
what was this? Something alive in the room! A man crouching
behind the table with a bundle of papers. It was Prosser ‘doing
something big’ at last. Too much astonished to move for a moment,
Sir Peter stood staring stupidly at the frightened, cowering figure
behind the table.
‘Hello: what are you doin’ here?’ said a voice in the doorway. Then
the American espied the broken desk, and a moment later the
Biologist found himself clutched by the collar, trying helplessly to
protect his head from a flailing fist, while Prosser’s shadow shot low
and horizontal through the doorway.
‘The Memoirs! the Memoirs!’ yelled the Biologist. ‘The d——d thief’s
stolen the Memoirs! Let me go! Let me go! It’s Prosser, not me! Oh,
for God’s sake, don’t hit me again!’
At the mention of Prosser the American stayed his hand, fumbled Sir
Peter’s pockets, then snatched him by the collar, and ran down the
stairs, dragging him after him like a live thing in a sack. But they
were too slow for Prosser. As they came out into Park Lane shouting
‘Stop thief! stop thief!’ there was the fat policeman saluting and
grinning delightedly.
‘He’s got clean away this time, sir.’
‘Heavens alive! Why didn’t you stop him?’
‘I knows my place, sir’—with a wink. ‘It’s only Mr. Prosser.’
‘Blow your whistle, man! Blow your whistle! He’s stolen State
Papers.’
The policeman walked very slowly forward to the edge of the
pavement and looked up and down the road, then turned about,
smiling rather nervously.
‘Do you reely mean it, sir?’
‘Good Lord!’ said the American, and started off running madly
without another word into Oxford Street; while the Biologist careered,
wild and hatless, up Grosvenor Street, yelling desperately ‘Prosser,
dear Prosser!’ to the scandal of Mayfair.
XXXVI
Among the many unnecessary things which Mr. Cato did in the
bewilderment of Dwala’s sudden illness, the most unnecessary was
to telegraph news of it to his sister, Lady Lillico.
‘Dwala ill lung hemorrhage doctors offer little hope recovery
Wyndham.’
They were in the drawing-room when the telegram came, just
preparing to go and dress for dinner.
‘How too perfectly frightful!’ cried Lady Lillico. ‘The Premier dying! I
must go at once.’
‘Good Lord, Louisa, what for?’ said her husband.
‘Don’t be so cynical, John. If Wyndham has telegraphed for me?’
‘Are you going to nurse the Prince?’
‘Of course I am. Pray keep your insinuations for some more fitting
time. What brutes men are! I believe you feel nothing even now!’ At
which she began to cry.
‘What about yer dinner?’
‘As if I could dine! Tell Hopkins to make up a little basket of
something to eat on the way. One mustn’t give any extra trouble. Oh
dear, oh dear; and my maid’s out! I shall have to take Emily. You
must send Harper on at once when she comes in.’
However, no feats of heroism were demanded of Lady Lillico. She
found Mr. Cato and Huxtable waiting for her with a comfortable meal
—Lady Wyse stayed with Dwala—for though the servants’ hall was
all agog with the events of the afternoon, and the butler darkly
prognosticated ‘the worst,’ things above stairs were in their usual
train. And when she presented herself an hour later, almost gay with
fine emotion, in a ‘business-like costume,’ cap and pinafore
complete, in the darkened sick-room, Lady Wyse, who hurried to the
door to check her entry—her violet eyes grown nearly black, and
looking ‘very wicked,’ as Lady Lillico said afterwards—told her baldly
that she would not be wanted till the morning.
XXXVII
When the sun cast his cold inquiring eye on England in the morning,
and the innocent fields awoke in their grey shifts of dew, the trains
that shot North, West, and South from London over the landscape,
like worldly thoughts in a house of prayer, bore the tidings of Dwala’s
disgrace. Trainloads of newspapers, the white wax sweated forth by
the grimy bees in the sleepless hives of the big city, rattled past
answering loads of milk and meat, gifts of the country, making the
daily exchange. Squires and parsons were too shocked to eat their
breakfast; their wives raced against the doctor to carry the news
from house to house; the schoolmasters told the children; the
children carried the tidings with the handkerchief of dinner to their
fathers under the trees in the field. There was no room for hesitation;
verdict and judgment were pronounced already. The country had
been made the victim of a hideous hoax. Dwala and all his works
must perish.
And yet, when the Biologist blurted his hint of a tail, a roomful of
people turned and rent him! It is the way of the world; it is part of
good manners. A partial revelation, a timid hint, an indiscretion, is
smothered ignominiously; when the whole blatant truth brays out,
men welcome it with ferocious joy. So, in the ancient days, tactless
young angels in Heaven were sent to Coventry who alluded to
Lucifer’s tail, or noticed anything odd about his feet; but when his
tumbling-day came at last, the Seraphim were in the very front of the
crowd which stood pelting meteors and yelling Caudate! ungulate!
down from the clouds.
Men shut up their shops in London and gathered about taverns and
corner-posts to unravel the sense of the bewildering news. Public
Opinion, deserting the grass of the Parks, slouched into the streets
to learn what it must do.
When Joey ran down into the street to fetch the morning milk, the
news stared out at her from the boards in pink and black: ‘Dwala, the
Missing Link!’
‘Golly!’ said her pals; ‘what’s your bloke been up to now?’
Joey was a heroine every day—the greatness of her acquaintance
had a savour in Seven Dials which it had lacked in Park Lane; but
this morning she soared altogether out of sight. What were milk-jugs
and breakfast to such a thing as this? The milk penny went in a
couple of newspapers, and she darted off with them across country
for Dwala’s house. Who knew but she might be the first to bring him
the great news?
Everybody was in the streets, as happens when public events are
astir; and every street sent forth a thin stream that trickled in the
same direction, till it formed a full river in Park Lane. A posse of
policemen guarded the spiked gates.
‘Move on! Move on!’ said the official voice.
‘None of your nonsense, constable; I’m a friend of the Missin’ Link.’
‘What! Miss Joey!’ beamed a familiar face from under a helmet. ‘Let
her in, Bill; she won’t ’urt ’im.’
The steps were littered with telegrams that lay like autumn leaves
unswept; and an anxious footman, muttering to himself, was
strapping a bag in the entry.
‘Is the Missin’ Link at home, young man?’
‘The brutes! To leave me behind, all alone!’
It was the last of the servants, deserted like an unwilling Casa
Bianca in the general flight, while packing his things in his cubicle. A
moment later he had gone too, without even looking at her, and she
stood alone in the empty, echoing hall. She could hear Hartopp
cursing and thumping with his wooden leg on the floor above. Then a
pistol-shot rang out somewhere in the house, and she was
frightened. While she stood hesitating which way to run a door
swung to, and Lady Wyse walked across the hall, with a basin
steaming in her hands. She went in at another door, and Joey
followed her, clutching her newspapers.
Dwala sat up in bed, propped against pillows, with ghastly, hollow
eyes; and on the chair beside him was Mr. Cato, pale and
dishevelled, fast asleep. A cold wave of disappointment surged over
Joey. Was this what Missing Links looked like? But he smiled at her,
and the old feeling of fellowship came back.
‘Have you heard the news?’ said Joey.
Dwala nodded. ‘What do they say?’
Joey read him column on column of frantic outcry, at all of which he
smiled gently.
‘This is our joke,’ he said, at last, to Lady Wyse.
‘It’s not our best.’
Then there came a tap at the door, and a gentle voice saying:
‘May I come in?’
Lady Lillico had been awoken by a dream with the sound of a shot in
it. Nine o’clock! Why, where was Harper? She rang, and rang in vain.
Then she looked out of window, and smiled and nodded at the
crowd. How sweet of them to be so anxious about the poor dear
Prince! And still no Harper. Never mind! One must expect to rough it
in a house of sickness. She knotted her hair and slipped on her
dressing-gown; a first visit in déshabillé lends a motherly grace to a
nurse’s part.
She tripped lightly down the silent stairs to Dwala’s room.
‘May I come in?’
She tip-toed up to the bed with a ceremonious face. Mr. Cato
frowned; Lady Wyse looked at her with cold curiosity.
‘Have you heard the news?’ said Joey, rustling a newspaper.
‘Evidently not,’ said Lady Wyse.
‘It’s all come out,’ said Mr. Cato, sepulchrally.
‘What’s come out?’ said his sister, scared. ‘I’ve heard nothing.’
Joey thrust the paper at her with an indicating finger.
She stared for a long time at the words without understanding; then
fell into a chair and laughed hysterically.
‘What do you think of it now they’ve caught it?’ whispered Dwala,
turning white eyes towards her.
‘Well, really, you ridiculous creature!’ she exclaimed, flapping at him
with a little lace handkerchief, half coquettishly, half as if keeping
something off. ‘It’s so out of the common.... The Prime Minister!...
One doesn’t know what to say!’
‘He’s dying,’ said Mr. Cato.
‘Wyndham! How can you!’
‘Lady Wyse must go and get some sleep now; you will take her
place.’
‘Don’t be idiotic! I should be no use. Oh dear, oh dear! Where can
Harper be?’
‘Sit down, Louisa!’ said Mr. Cato sternly, barring her way. ‘Lady Wyse
has been up all night.’
‘Don’t be so cruel.... Let me go! let me go!’ she screamed in an
access of sudden fear, wrenched herself free from him, and ran
towards the door.
Then abruptly her horror leaped up and overwhelmed her; the
instinct of flying from the incomprehensible—the instinct of the horse
which shies at a piece of moving paper—was swallowed up in the
nightmare of realising that the impossible had happened, was in this
very room with her. This man she had come to nurse, this man with
whom she had talked and shaken hands, was suddenly not a man,
but something unknown and monstrous, of another world. Her
faculties failed, as at sight of a ghost, not in fear of injury, but in the
mere awfulness of the alien power. She staggered out at the door
crying ‘Save me! save me!’ threw her hands forward in her first
natural gesture since childhood, and fell swooning in the hall. When
she came back to consciousness, after long journeying in nightmare
worlds, she heard angry voices speaking near her.
‘Let me out, d—— you!’ said Hartopp—that dreadful Mr. Hartopp
—‘they’re throwing stones at my windows, I tell you. They’ll smash
my china! Let me get at the brutes!’
‘This door ain’t goin’ to be opened till the Prince is re-moved.’
It was the American who answered him. He stood with his hat on,
leaning against the barred and bolted hall-door, his arms folded and
a pistol drooping from either hand.
‘D—— the ——!’ said Hartopp. ‘Why don’t you chuck him out and
have done with it? It’s all his fault.’
‘Thank God you’re back!’ said Lady Wyse’s voice right over Lady
Lillico’s head. ‘Have you arranged it?’
‘The Boss is agreeable,’ said the American. ‘The “Phineas” will be at
Blackwall at twelve o’clock, steam up. One of his vans is waitin’
down back in Butlin Street now, and we must shift the Prince at
once, before any onpleasantness begins. There was no other way;
the Prince will hev to go as an anamal.’
A stone came jingling through the window beside them, and others
followed in showers.
‘B—— brutes!’ said the blind man.
‘Where’s Huxtable?’ said Lady Wyse.
‘Huxtable’s gone.’
‘Skunk!’ said Joey.
‘Not quite a skunk,’ said the American; ‘“skunk” is goin’ too fur.’
There was a roar and a rush outside, battle cries, shrieks of
despairing whistles, and a moment later a heavy battering at the
mahogany of the front door.
Lady Lillico, fully conscious at last, jumped up with piercing yells.
She ran this way and that, bewildered.
‘We must get the Prince away quickly,’ said Lady Wyse, going
towards his room.
‘Oh, let me out, let me out somewhere!’ cried Lady Lillico. Joey ran
past with her tongue thrust mockingly forth, like a heraldic lion
gardant.
‘Here, give me your pistols,’ said the blind man; ‘I’ll give the brutes
what for!’
Slowly and heavily they carried Dwala out across the hall, wrapped
in his blankets like a gigantic mummy; while Hartopp stood in an
expectant joy of ferocity guarding the entrance. Down the kitchen
passage they carried him, and out into the high-walled garden—with
Lady Lillico flitting like a Banshee before them—through the stable-
yard, and into the deserted street, where the van was waiting for
them. Public Opinion, so rigorous once in its denunciation of ‘frontal
attacks,’ seemed to have forgotten the ‘lessons of the Boer War.’
When the big door was battered down, and the furious crowd broke
in, half a dozen of them fell mortally wounded before Hartopp was
overpowered. The old Fence died, fighting like a tiger for his
property.

What was Dwala thinking of as he lumbered slowly through the


length of London in that menagerie van? Was he laughing quietly to
himself at the thought that he, the saviour of England, the
superhuman mind, was being hustled secretly out of England, for a
trivial pride of species, as if he had committed some unspeakable
crime? Was he weeping at the nearness of his separation from this
handful of faithful friends? Probably not. His mind, withdrawn to the
innermost darkness of the caves, was probably busy with the trivial
thoughts which beset men at such times. It is only in the last moment
that the soul throws off the load of little things, and, soaring like a
bird, sees Life and Death spreading in their vastness beneath it. He
lay still, with his eyes shut, and his temples hollow with decay. Lady
Lillico was fast asleep, under a black cloak which somebody had
thrown over her. The rest sat silent in the jolting twilight with their feet
in the straw.
‘It’s a lesson for all of us,’ murmured Mr. Cato at last.
‘It’s that,’ said the American; ‘it p’ints a moral sharp enough to hurt.’

As Mr. Cato stood with Joey on the jetty, watching the last moments
of departure, the American came to the bulwarks with Lady Wyse,
and, leaning over, beckoned him.
‘“Skunk” was goin’ too fur for Huxtable. I’ve just bin tellin’ Lady Wyse;
he shot himself whin the noos came. I found him lyin’ in his room.’
‘Was he dead?’ murmured Mr. Cato, awestruck at the fall of an
enemy.
The American nodded.
‘Deader’n a smelt.’
‘I wish I were dead too!’ said Mr. Cato bitterly.
The American made a motion of diving with his joined hands. Mr.
Cato shook his head.
‘I have my two sisters to look after.’
‘I wish you joy.’
Then the cables were loosed, the screw snorted in the water, the
American waved, and followed Lady Wyse into the cabin; the boat
slid away from the jetty, and, slowly turning in mid-stream, reared its
defiant head towards the sea.

After many days of alert and passive silence, Dwala died on his
pallet on the deck. He turned his face sideways down into the pillow,
as if to hide the smile that was rising to his lips; then breathed one
deep, luxurious sigh, and was ended. They wrapped him in sacking,
with an iron reel at his feet; and in the cold, clear morning, when the
sun mounted flat and yellow to its daily course and the low mists
smoked this way and that along the waves, they slid him without a
word off a door and over the bulwarks.
Down, down through the crystal indifference, wavering gently to his
appointed place in the rocky bottom of the rapt thicket of weeds;
losing the last remnant of individuality as the motion ceased;
indistinguishable from a little heap of sand; lying careless and
obscure, like some tired animal which has crept to rest in the wild
garden of a crumbled castle in an empty world, long since
abandoned and forgotten by mankind.
The ‘Phineas’ paused for a moment in mid-ocean, the only living
thing of its tribe upon the waters without a purpose straining in its
hull. The hesitation lasted only a moment. The boat swung round,
took one look at the horizon, then dashed forwards again on the
home journey to England and new work.
England had gone back to its occupations. The papers spoke of the
return of political sanity; of the rejection of ideas from a tainted
source; of the restoration of the system which had been the bulwark
of our greatness through so many centuries. The composition of
Lord Glendover’s Cabinet attested his sincere intention of putting
public affairs on a business-like and efficient footing.
There is no remedy for the errors of Democracy; there is no elasticity
of energy to fulfil purposes conceived on a larger scale than its
every-day thought. Other systems may be purged by the rising
waves of national life; but Democracy is exhaustive.
PRINTED BY
SPOTTISWOODE AND CO. LTD., NEW-STREET SQUARE
LONDON
BY THE SAME AUTHOR.
THIRD IMPRESSION. With 16 Illustrations by the Author.
Crown 8vo. 3s. 6d.

DOWNY V. GREEN,
RHODES SCHOLAR AT OXFORD.

PRESS OPINIONS.
TIMES.—‘We never remember to have read anything
which more compelled laughter than these too-few pages.
We have a perfect carnival of American slang.... The line
illustrations, which are by the author, are in some cases
admirable; we may say comparable with Mr. Kipling’s.’
DAILY TELEGRAPH.—‘It is one of the best bits of fooling
we have read for a long time, and is written by one who
knows Oxford perfectly, and has a command of American
slang which Mark Twain himself might envy.... This little
book, which is cleverly illustrated by the author, deserves
as wide a vogue as its predecessor “Verdant.” Its humour
is quite as irresistible and more subtle.’
PALL MALL GAZETTE.—‘A delightful skit.... We do not
think anyone has hit off better than Mr. Calderon the
extraordinary cocksureness, volubility, and linguistic
exuberance of the typical American, yet he never allows
his humour to get out of hand. The Oxford characters are
marked with the same sureness of touch.’
GUARDIAN.—‘If one must compare Downy with Verdant,
the descendant’s experiences are the better for being
written by an Oxford man, while Verdant’s were not. The
satire is as admirable as the farce; but, on the whole,
Downy as Verdant makes one rather laugh aloud than
smile.’
WORLD.—‘The fun is kept up with an unflagging spirit and
ingenuity that render the skit—which the author has
embellished with some diverting illustrations from his own
evidently facile pencil—a by no means unworthy
comparison to “Verdant Green” itself.’
OXFORD MAGAZINE.—‘Mr. Downy V. Green is an
American grandson of the immortal Verdant, and it is not
too much to say that he is fully worthy of his lineage. From
the moment one embarks upon his adventures it is difficult
to lay them down. Mr. Calderon has a biting humour, and
spares neither Oxford nor America.’
MANCHESTER GUARDIAN.—‘A really capital narrative,
in which an accurate knowledge of Oxford life is combined
with a marvellously wide knowledge of the American
language.... Nothing is more admirable than the fertility
which enables him to avoid employing English without
making his substitute for it grow tedious.’
SPECTATOR.—‘Our readers may take our assurance that
the book is amusing in a high degree.’
ATHENÆUM.—‘Mr. Calderon has an amazing command
of picturesque slang and metaphor from overseas, and, as
befits the son of a late distinguished artist, has himself
provided excellent illustrations of his ideas.’
DAILY MAIL.—‘Most excellent fooling.... His sketches
possess a crude, rude vigour that remind the faithful of the
immortal pencil of Michael Angelo Titmarsh. He has it in
him to become a humorist of the first order.’
VARSITY.—‘The whole book is full of rollicking humour
from cover to cover.’
GLASGOW HERALD.—‘The book is capitally written, and
evidently from a first-hand knowledge of student life. It is
full of humour—American humour and Oxford humour—
and is altogether an excellent book of its kind.’
ILLUSTRATED EDITIONS
OF

POPULAR WORKS.
Handsomely bound in cloth gilt, each volume containing Four
Illustrations. Crown 8vo. 3s. 6d. each.
THE SMALL HOUSE AT ALLINGTON. By Anthony
Trollope.
FRAMLEY PARSONAGE. By Anthony Trollope.
THE CLAVERINGS. By Anthony Trollope.
TRANSFORMATION: a Romance. By Nathaniel
Hawthorne.
DOMESTIC STORIES. By the Author of ‘John Halifax,
Gentleman.’
THE MOORS AND THE FENS. By Mrs. J. H. Riddell.
WITHIN THE PRECINCTS. By Mrs. Oliphant.
CARITÀ. By Mrs. Oliphant.
FOR PERCIVAL. By Margaret Veley.
NO NEW THING. By W. E. Norris.
LOVE THE DEBT. By Richard Ashe King (‘Basil’).
WIVES AND DAUGHTERS. By Mrs. Gaskell.
NORTH AND SOUTH. By Mrs. Gaskell.
SYLVIA’S LOVERS. By Mrs. Gaskell.
CRANFORD, and other Stories. By Mrs. Gaskell.
MARY BARTON, and other Stories. By Mrs. Gaskell.
RUTH; THE GREY WOMAN, and other Stories. By Mrs.
Gaskell.
LIZZIE LEIGH; A DARK NIGHT’S WORK, and other
Stories. By Mrs. Gaskell.

You might also like