Copyright....8
Table of Contents....9
Preface....19
Who Should Read This Book....20
Conventions Used in This Book....20
Using Code Examples....21
O’Reilly Online Learning....22
How to Contact Us....22
Acknowledgments for the 2nd Edition....23
Acknowledgments for the 1st Edition....23
Chapter 1. Setting Up Your Go Environment....25
Installing the Go Tools....25
Troubleshooting Your Go Installation....26
Go Tooling....26
Your First Go Program....27
Making a Go Module....27
go build....28
go fmt....29
go vet....31
Choose Your Tools....32
Visual Studio Code....32
GoLand....33
The Go Playground....34
Makefiles....36
The Go Compatibility Promise....37
Staying Up-to-Date....38
Exercises....38
Wrapping Up....39
Chapter 2. Predeclared Types and Declarations....41
The Predeclared Types....41
The Zero Value....41
Literals....42
Booleans....43
Numeric Types....44
A Taste of Strings and Runes....49
Explicit Type Conversion....50
Literals Are Untyped....51
var Versus :=....52
Using const....54
Typed and Untyped Constants....56
Unused Variables....56
Naming Variables and Constants....57
Exercises....59
Wrapping Up....60
Chapter 3. Composite Types....61
Arrays—Too Rigid to Use Directly....61
Slices....63
len....65
append....65
Capacity....66
make....67
Emptying a Slice....68
Declaring Your Slice....69
Slicing Slices....70
copy....73
Converting Arrays to Slices....74
Converting Slices to Arrays....75
Strings and Runes and Bytes....76
Maps....80
Reading and Writing a Map....81
The comma ok Idiom....82
Deleting from Maps....83
Emptying a Map....83
Comparing Maps....83
Using Maps as Sets....84
Structs....85
Anonymous Structs....87
Comparing and Converting Structs....88
Exercises....89
Wrapping Up....90
Chapter 4. Blocks, Shadows, and Control Structures....91
Blocks....91
Shadowing Variables....92
if ....95
for, Four Ways....96
The Complete for Statement....96
The Condition-Only for Statement....97
The Infinite for Statement....98
break and continue....99
The for-range Statement....100
Labeling Your for Statements....106
Choosing the Right for Statement....107
switch....108
Blank Switches....111
Choosing Between if and switch....113
goto—Yes, goto....113
Exercises....116
Wrapping Up....116
Chapter 5. Functions....117
Declaring and Calling Functions....117
Simulating Named and Optional Parameters....118
Variadic Input Parameters and Slices....119
Multiple Return Values....120
Multiple Return Values Are Multiple Values....121
Ignoring Returned Values....121
Named Return Values....122
Blank Returns—Never Use These!....123
Functions Are Values....124
Function Type Declarations....127
Anonymous Functions....127
Closures....129
Passing Functions as Parameters....131
Returning Functions from Functions....132
defer....133
Go Is Call by Value....138
Exercises....140
Wrapping Up....141
Chapter 6. Pointers....143
A Quick Pointer Primer....143
Don’t Fear the Pointers....147
Pointers Indicate Mutable Parameters....149
Pointers Are a Last Resort....153
Pointer Passing Performance....154
The Zero Value Versus No Value....155
The Difference Between Maps and Slices....155
Slices as Buffers....159
Reducing the Garbage Collector’s Workload....160
Tuning the Garbage Collector....163
Exercises....165
Wrapping Up....165
Chapter 7. Types, Methods, and Interfaces....167
Types in Go....167
Methods....168
Pointer Receivers and Value Receivers....169
Code Your Methods for nil Instances....172
Methods Are Functions Too....173
Functions Versus Methods....174
Type Declarations Aren’t Inheritance....174
Types Are Executable Documentation....175
iota Is for Enumerations—Sometimes....176
Use Embedding for Composition....178
Embedding Is Not Inheritance....180
A Quick Lesson on Interfaces....181
Interfaces Are Type-Safe Duck Typing....182
Embedding and Interfaces....186
Accept Interfaces, Return Structs....186
Interfaces and nil....188
Interfaces Are Comparable....189
The Empty Interface Says Nothing....190
Type Assertions and Type Switches....191
Use Type Assertions and Type Switches Sparingly....194
Function Types Are a Bridge to Interfaces....197
Implicit Interfaces Make Dependency Injection Easier....198
Wire....202
Go Isn’t Particularly Object-Oriented (and That’s Great)....202
Exercises....202
Wrapping Up....203
Chapter 8. Generics....205
Generics Reduce Repetitive Code and Increase Type Safety....205
Introducing Generics in Go....208
Generic Functions Abstract Algorithms....211
Generics and Interfaces....212
Use Type Terms to Specify Operators....214
Type Inference and Generics....217
Type Elements Limit Constants....217
Combining Generic Functions with Generic Data Structures....218
More on comparable....220
Things That Are Left Out....222
Idiomatic Go and Generics....223
Adding Generics to the Standard Library....225
Future Features Unlocked....225
Exercises....225
Wrapping Up....226
Chapter 9. Errors....227
How to Handle Errors: The Basics....227
Use Strings for Simple Errors....229
Sentinel Errors....229
Errors Are Values....232
Wrapping Errors....234
Wrapping Multiple Errors....236
Is and As....238
Wrapping Errors with defer....241
panic and recover....242
Getting a Stack Trace from an Error....244
Exercises....245
Wrapping Up....245
Chapter 10. Modules, Packages, and Imports....247
Repositories, Modules, and Packages....247
Using go.mod....248
Use the go Directive to Manage Go Build Versions....249
The require Directive....250
Building Packages....251
Importing and Exporting....251
Creating and Accessing a Package....251
Naming Packages....254
Overriding a Package’s Name....254
Documenting Your Code with Go Doc Comments....255
Using the internal Package....258
Avoiding Circular Dependencies....259
Organizing Your Module....260
Gracefully Renaming and Reorganizing Your API....262
Avoiding the init Function if Possible....263
Working with Modules....264
Importing Third-Party Code....264
Working with Versions....269
Minimal Version Selection....271
Updating to Compatible Versions....272
Updating to Incompatible Versions....272
Vendoring....274
Using pkg.go.dev....275
Publishing Your Module....275
Versioning Your Module....276
Overriding Dependencies....278
Retracting a Version of Your Module....279
Using Workspaces to Modify Modules Simultaneously....279
Module Proxy Servers....283
Specifying a Proxy Server....283
Using Private Repositories....284
Additional Details....284
Exercises....285
Wrapping Up....285
Chapter 11. Go Tooling....287
Using go run to Try Out Small Programs....287
Adding Third-Party Tools with go install....288
Improving Import Formatting with goimports....290
Using Code-Quality Scanners....291
staticcheck....292
revive....293
golangci-lint....294
Using govulncheck to Scan for Vulnerable Dependencies....296
Embedding Content into Your Program....298
Embedding Hidden Files....301
Using go generate....302
Working with go generate and Makefiles....305
Reading the Build Info Inside a Go Binary....305
Building Go Binaries for Other Platforms....307
Using Build Tags....308
Testing Versions of Go....309
Using go help to Learn More About Go Tooling....310
Exercises....310
Wrapping Up....310
Chapter 12. Concurrency in Go....311
When to Use Concurrency....311
Goroutines....313
Channels....315
Reading, Writing, and Buffering....315
Using for-range and Channels....316
Closing a Channel....316
Understanding How Channels Behave....317
select....318
Concurrency Practices and Patterns....321
Keep Your APIs Concurrency-Free....321
Goroutines, for Loops, and Varying Variables....322
Always Clean Up Your Goroutines....323
Use the Context to Terminate Goroutines....324
Know When to Use Buffered and Unbuffered Channels....325
Implement Backpressure....326
Turn Off a case in a select....328
Time Out Code....328
Use WaitGroups....330
Run Code Exactly Once....332
Put Your Concurrent Tools Together....333
When to Use Mutexes Instead of Channels....337
Atomics—You Probably Don’t Need These....341
Where to Learn More About Concurrency....341
Exercises....341
Wrapping Up....342
Chapter 13. The Standard Library....343
io and Friends....343
time....348
Monotonic Time....350
Timers and Timeouts....351
encoding/json....351
Using Struct Tags to Add Metadata....351
Unmarshaling and Marshaling....353
JSON, Readers, and Writers....354
Encoding and Decoding JSON Streams....355
Custom JSON Parsing....356
net/http....360
The Client....360
The Server....361
ResponseController....366
Structured Logging....368
Exercises....371
Wrapping Up....371
Chapter 14. The Context....373
What Is the Context?....373
Values....376
Cancellation....382
Contexts with Deadlines....387
Context Cancellation in Your Own Code....391
Exercises....392
Wrapping Up....393
Chapter 15. Writing Tests....395
Understanding the Basics of Testing....395
Reporting Test Failures....397
Setting Up and Tearing Down....397
Testing with Environment Variables....400
Storing Sample Test Data....400
Caching Test Results....401
Testing Your Public API....401
Using go-cmp to Compare Test Results....402
Running Table Tests....404
Running Tests Concurrently....406
Checking Your Code Coverage....408
Fuzzing....410
Using Benchmarks....417
Using Stubs in Go....421
Using httptest....426
Using Integration Tests and Build Tags....429
Finding Concurrency Problems with the Data Race Detector....430
Exercises....432
Wrapping Up....432
Chapter 16. Here Be Dragons: Reflect, Unsafe, and Cgo....433
Reflection Lets You Work with Types at Runtime....434
Types, Kinds, and Values....435
Make New Values....439
Use Reflection to Check If an Interface’s Value Is nil....441
Use Reflection to Write a Data Marshaler....441
Build Functions with Reflection to Automate Repetitive Tasks....446
You Can Build Structs with Reflection, but Don’t....447
Reflection Can’t Make Methods....448
Use Reflection Only if It’s Worthwhile....448
unsafe Is Unsafe....449
Using Sizeof and Offsetof....450
Using unsafe to Convert External Binary Data....452
Accessing Unexported Fields....456
Using unsafe Tools....457
Cgo Is for Integration, Not Performance....457
Exercises....462
Wrapping Up....462
Index....465
About the Author....493
Colophon....493
Go has rapidly become the preferred language for building web services. Plenty of tutorials are available to teach Go's syntax to developers with experience in other programming languages, but tutorials aren't enough. They don't teach Go's idioms, so developers end up recreating patterns that don't make sense in a Go context. This practical guide provides the essential background you need to write clear and idiomatic Go.
No matter your level of experience, you'll learn how to think like a Go developer. Author Jon Bodner introduces the design patterns experienced Go developers have adopted and explores the rationale for using them. This updated edition also shows you how Go's generics support fits into the language.