Download Complete Go by Example MEAP Programmer s guide to idiomatic and testable code Inanc Gumus PDF for All Chapters
Download Complete Go by Example MEAP Programmer s guide to idiomatic and testable code Inanc Gumus PDF for All Chapters
com
https://ebookfinal.com/download/go-by-example-meap-
programmer-s-guide-to-idiomatic-and-testable-code-inanc-
gumus/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookfinal.com/download/ruby-by-example-concepts-and-code-1st-
edition-kevin-c-baird/
ebookfinal.com
https://ebookfinal.com/download/go-in-practice-second-edition-
meap-v02-nathan-kozyra/
ebookfinal.com
https://ebookfinal.com/download/xna-4-0-game-development-by-example-
beginner-s-guide-visual-basic-edition-kurt-jaegers/
ebookfinal.com
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
https://ebookfinal.com/download/information-theory-and-coding-by-
example-kelbert-mark/
ebookfinal.com
https://ebookfinal.com/download/systems-programmer-s-guide-to-z-os-
system-logger-1st-ed-edition-ibm-redbooks/
ebookfinal.com
https://ebookfinal.com/download/sas-functions-by-example-second-
edition-ron-cody/
ebookfinal.com
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:
—Inanc Gumus
In this book
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.
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.
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
— H. Abelson and G.J. Sussman, from the book Structure and Interpretation
of Computer Programs
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.
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.
— Heraclitus
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.
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.
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
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.
Note
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
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
Figure 1.1 Go compiles code with all necessary dependencies into a single binary.
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
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.
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:
Note
Note
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.
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.
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.
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).
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.
Note
1.7.3 Channels
"Share memory by communicating, don't communicate by sharing
memory."
— Go Proverb
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.
1.7.4 Wrap up
"If all you have is a hammer, everything looks like a nail."
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.
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.
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.
Note
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.
Note
Chapter 2 (Section 2.4.1) explains struct types, and Chapter 9 (Section 9.3.1)
explores embedding in more detail.
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.
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.
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.
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.
Note
Chapter 9 explains how to structure and write HTTP servers in detail.
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!")
}
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.
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.
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.
Note
2.1 Packages
We'll start with a simple executable program example that prints this book's
title.
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:
Definition
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.
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.
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.
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.
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.
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
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.
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.
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
2.1.6 Exercises
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.
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.
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)
Note
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
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.
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
Note
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.
package main
import "fmt"
func main() {
counter := 42
incrVal(counter) #A
fmt.Println(counter) // 42
incrPtr(&counter) #B
fmt.Println(counter) // 43
}
Figure 2.5 Pointers enable us to mutate original values without copying them. Numbers below are
the memory addresses of each variable.
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.
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.
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
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.
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.
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.
package main
func main() {
selfie := [resolution8K]byte{ /* ..color data.. */ } #B
invertColors(selfie)
}
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.
package main
func main() {
selfie := [resolution8K]byte{ /* pixel data */ }
invertColors(&selfie) #A
}
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.
Wrap up
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.
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.