Have you ever used strings.Split or http.Get and wondered “what is actually happening under the hood”? With Go, you have a massive advantage: the standard library is written in the language itself, it is remarkably readable, and best of all, it is already on your machine. There is no need to dig through obscure repositories or make wild guesses. In this guide, we will learn how to read it step by step, using real-world examples and hands-on exercises so you can practice on your own.
This guide is designed both for those just getting started with Go and for developers who use it daily but have never dared to open its source code. You don’t need to be a language expert; having written a few simple programs is more than enough. This is the third installment in a series: in the first, we explored why Go is the way it is, and in the second, we built a concurrent URL checker. Here, we will pop the hood and look inside.
How to use this guide
Each section follows the same pattern: a brief explanation, a code example, and a Try it yourself block with an exercise. Solutions can be found in the appendix (at the very end). Standard library snippets are taken from Go 1.24 and have been trimmed down to fit well here. Always inspect the actual source code on your machine, as it can vary slightly between Go releases.
| Section | Level | What you will see |
|---|---|---|
| 1 | Basic | Core concepts and navigation tools |
| 2 | Basic | A type, a method, and a fundamental Go idea |
| 3 | Intermediate | io.Reader and io.Writer |
| 4 | Intermediate | What actually happens during append |
| 5 | Advanced | sync.Once and sync.WaitGroup |
| 6 | Advanced | Where to go next and how to contribute |
1. The basics and your tools
Level: Basic
Before diving into the code, keep five core Go concepts in mind. You do not need to memorize every nuance; just recognize them when they pop up:
- Zero values: every variable has a default value (0,
"",nil…) even if you do not explicitly initialize it. - Slices and maps: everyday collections. A slice is essentially a “window” over an underlying array.
- Pointers:
&xgives you the memory address ofx, and*pyields the value pointed to byp. You will see them often in method receivers such asfunc (e *errorString) Error(). - Interfaces: a set of method signatures. A type satisfies an interface simply by implementing those methods, with no explicit declaration required.
- Errors as values:
erroris just an interface with a single method,Error() string.
Your tools
- Terminal
go doc: runninggo doc strings.Splitshows documentation, and appending-srcreveals the source code. - pkg.go.dev: documentation for all packages, featuring direct links to the source code of every function.
- Your editor: in VS Code with the official Go extension (powered by
gopls), hit F12 on any function to jump straight to its definition, including standard library symbols. go env GOROOT: shows where Go is installed on your machine. The standard library lives inside thesrcfolder at that path.
Let’s test go doc with an actual function:
go doc -src strings.Contains
func Contains(s, substr string) bool {
return Index(s, substr) >= 0
}
A single line! Contains barely does anything on its own: it delegates to Index to find the position of the substring and checks whether it is non-negative. This is the first reading habit worth cultivating: standard library functions are often much shorter than you might expect, and they almost always delegate work to other internal functions.
Try it yourself: run go doc -src strings.HasPrefix. This time you will not find the comparison right away, but rather a call to another package. Follow the trail (using F12) until you track down the actual comparison. Which package contains it? Check the appendix for the answer.
2. Your first read: errors.New
Level: Basic
Let’s start with one of Go’s shortest and most widely used functions. Run go doc -src errors.New (or check the file src/errors/errors.go); stripped of comments, this is all there is:
func New(text string) error {
return &errorString{text}
}
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
Let’s break it down:
errorStringis a struct containing a single field: the error text.- It has an
Error() stringmethod. That alone satisfies theerrorinterface, without needing anyimplementskeyword. Newreturns&errorString{text}: a pointer to a newly allocated struct, not a value.
That last detail explains something that often confuses newcomers. The official docs state it clearly: every call to New returns a distinct value, even when the provided message is identical. Think of two ID cards bearing the same name: they display identical text, but they are separate cards. Verify it yourself:
a := errors.New("algo salió mal")
b := errors.New("algo salió mal")
c := a
fmt.Println(a == b) // false: mismo texto, distinto error
fmt.Println(a == c) // true: es el mismo error
This is why, in idiomatic Go, sentinel errors are declared once as package-level variables (io.EOF being the classic example) and compared directly against that instance.
Try it yourself: create your own custom error type ErrorEdad (or AgeError) with an Age int field and an Error() method. Write a validate(age int) error function that returns it whenever the age is negative, and use errors.As in the caller to inspect the underlying value. Try solving it before checking the solution.
3. Interfaces in action: io.Reader and io.Writer
Level: Intermediate
These are two of Go’s most compact and powerful interfaces. Each exposes just a single method:
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
Files, network sockets, HTTP responses, in-memory buffers… all satisfy at least one of these two interfaces. They work like standard power outlets: any appliance (Reader) plugs into any socket (Writer), which is why a function like io.Copy works seamlessly across nearly every scenario without requiring rewrites.
Reading a real Reader
Take a look at how strings.Reader implements it (the reader produced by strings.NewReader):
func (r *Reader) Read(b []byte) (n int, err error) {
if r.i >= int64(len(r.s)) {
return 0, io.EOF
}
r.prevRune = -1
n = copy(b, r.s[r.i:])
r.i += int64(n)
return
}
The reader tracks its current position in r.i. It copies as much data into b as will fit, advances its internal offset, and once nothing remains, returns io.EOF: a “normal” sentinel error meaning “end of data”. The prevRune line is an internal implementation detail you can safely ignore for now; knowing what to overlook is an essential part of reading source code.
And now io.Copy
io.Copy is essentially a one-liner that delegates to copyBuffer, which reveals a clever design detail. Before performing the copy loop, it checks if either endpoint can handle the operation directly and more efficiently on its own:
if wt, ok := src.(WriterTo); ok {
return wt.WriteTo(dst)
}
if rf, ok := dst.(ReaderFrom); ok {
return rf.ReadFrom(src)
}
The type assertion src.(WriterTo) asks: “does this value also implement the WriteTo method?”. If so, it takes that optimized shortcut. Only if neither end implements an optimized interface does it allocate a 32 KB buffer and copy data in a straightforward Read and Write loop.
Let’s test this with a custom Writer that simply counts bytes:
type Contador struct{ Bytes int }
func (c *Contador) Write(p []byte) (int, error) {
c.Bytes += len(p)
return len(p), nil
}
func main() {
var c Contador
n, err := io.Copy(&c, strings.NewReader("Hola, Go"))
fmt.Println(n, c.Bytes, err) // 8 8 <nil>
}
Try it yourself: write an UppercaseReader (or Mayusculas) type that wraps another io.Reader and converts everything it reads to uppercase (ASCII letters only). Test it with:
io.Copy(os.Stdout, Mayusculas{strings.NewReader("hola desde go\n")})
Hint: your Read method should call the wrapped reader’s Read first, then mutate the resulting bytes in-place.
4. Slices under the hood: what happens during append
Level: Intermediate
A slice is a window over an underlying array: it stores a pointer to the array, a length (len), and a capacity (cap). As long as remaining capacity exists, append writes into the existing array. Once capacity is exhausted, Go allocates a larger array and copies the data over. But how much larger? The answer lives in src/runtime/slice.go, inside a function called nextslicecap (presented here without comments and trimmed at the end):
func nextslicecap(newLen, oldCap int) int {
newcap := oldCap
doublecap := newcap + newcap
if newLen > doublecap {
return newLen
}
const threshold = 256
if oldCap < threshold {
return doublecap
}
for {
newcap += (newcap + 3*threshold) >> 2
if uint(newcap) >= uint(newLen) {
break
}
}
// ...
return newcap
}
Here is the logic in plain terms:
- If your new required capacity is more than double the current capacity, it allocates exactly what you requested.
- If the slice’s capacity is under 256 elements, it doubles it.
- From 256 onwards, growth slows down: roughly 25% larger, plus a small constant factor that smooths the transition.
Let’s see it in action. This snippet logs whenever the capacity changes:
var s []int
anterior := -1
for i := 0; i < 2000; i++ {
s = append(s, i)
if cap(s) != anterior {
fmt.Printf("len=%d cap=%d\n", len(s), cap(s))
anterior = cap(s)
}
}
Approximate output:
len=1 cap=1
len=2 cap=2
len=3 cap=4
len=5 cap=8
len=9 cap=16
len=17 cap=32
len=33 cap=64
len=65 cap=128
len=129 cap=256
len=257 cap=512
len=513 cap=848
len=849 cap=1280
len=1281 cap=1792
len=1793 cap=2560
Up to 256, capacity doubles exactly as described. After 512, you see 848 rather than what the raw mathematical formula would yield (832). This is expected: after computing the target capacity, the runtime rounds it up to match available memory allocator block sizes, so exact figures may vary slightly across architectures and Go versions.
A classic pitfall
Because slices share an underlying array, an append call on one slice can silently overwrite data in another:
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99)
fmt.Println(a, b) // [1 2 99 4] [1 2 99]
b has a capacity of 4, so appending 99 fits right into the shared array, overwriting the 3 in a.
Try it yourself:
- Without running any code, what is the capacity of an empty
[]intslice after performing 5 consecutiveappendoperations? - What changes in the previous snippet if you slice it as
b := a[:2:2]?
Check the appendix for answers.
5. Concurrency in the standard library
Level: Advanced
You previously used sync.WaitGroup in the concurrent URL checker. Now let’s explore the internals of two key components in the sync package. If atomic operations feel slightly heavy at first, don’t worry: grasp the high-level pattern and revisit the details later.
sync.Once: running an action exactly once
sync.Once guarantees that a function executes only once, even when invoked by multiple goroutines concurrently. It is ideal for expensive lazy initializations. Omitting comments, its core logic looks like this:
type Once struct {
_ noCopy
done atomic.Uint32
m Mutex
}
func (o *Once) Do(f func()) {
if o.done.Load() == 0 {
o.doSlow(f)
}
}
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done.Load() == 0 {
defer o.done.Store(1)
f()
}
}
Picture a door with a lock. First, Do checks whether the door is already open (done is 1) via a non-blocking load: if so, execution returns immediately. Otherwise, it falls back to doSlow, where only one goroutine at a time acquires the lock (Lock). Inside, it rechecks done—since another goroutine might have slipped in just before—and executes f. The defer o.done.Store(1) marks execution as complete once f finishes, even if f panics.
Notice the comment in the real source code: it explains why a straightforward CompareAndSwap is insufficient. With CAS, a second goroutine would return immediately while the first was still actively executing f, violating Do’s guarantee that f has fully completed before returning.
Let’s test it with five goroutines attempting to run the same function:
var once sync.Once
var wg sync.WaitGroup
veces := 0
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
once.Do(func() { veces++ })
}()
}
wg.Wait()
fmt.Println("la función se ejecutó", veces, "vez") // la función se ejecutó 1 vez
sync.WaitGroup: a single number with two counters
If you inspect src/sync/waitgroup.go, the first surprising detail is that WaitGroup stores its entire internal state inside a single 64-bit atomic integer (state atomic.Uint64). As the code comments clarify, the top 32 bits hold the pending task counter, while the bottom 32 bits track the number of waiting goroutines. Add and Done modify the task counter, and Wait blocks until it reaches zero.
Try it yourself: since Go 1.21, the standard library includes sync.OnceValue, which invokes a function once and caches its return value. Use it to “compute” the number 42 exactly once and read it twice. Confirm that your calculating... log message prints only once.
6. Real projects and next steps
Level: Advanced
The standard library makes an outstanding training ground, but sooner or later you will want to read larger codebases. The approach remains the same:
- Start with documentation and test suites.
_test.gofiles demonstrate how the code is expected to be used in practice. - Locate the primary entry point: the
mainfunction or the core type exported by the package. - Trace a single end-to-end execution path (one request, one CLI command) jumping from definition to definition using F12.
- Pay close attention to interfaces. They show how components interact without forcing you to understand every implementation detail.
- Run what you read:
go test -run TestNamelets you isolate and step through a specific scenario.
Great places to practice
net/http: start by examiningtype Handler interface, whose sole method isServeHTTP(ResponseWriter, *Request). The entire package revolves around that abstraction.bufio.Scanner: we used it in the URL checker to read line by line. Opensrc/bufio/scan.goand compare how it works against your assumptions.- A popular CLI tool: pick a tool you use every day, clone its repository, and trace what happens when you execute a command.
Your first contribution
You don’t have to start by writing complex code. Fixing documentation typos or contributing a missing example is a legitimate contribution. For the Go project itself, start with the official contribution guide, which recommends opening an issue tracker proposal before working on significant changes. Third-party projects typically maintain a CONTRIBUTING.md file detailing their workflow.
Resources
- A Tour of Go: the official interactive tour.
- Effective Go: guide to writing clean, idiomatic Go.
- Go by Example: bite-sized examples across core topics.
- pkg.go.dev: documentation for all packages, linked to source code.
- The Go Programming Language Specification: the language reference, surprisingly readable.
Mini glossary
| Term | Meaning |
|---|---|
| Package | A collection of Go source files in the same directory, imported together |
| Module | A versioned collection of packages defined by a go.mod file |
| Interface | A set of method signatures that a type satisfies implicitly |
| Receiver | The instance on which a method is defined, such as (e *errorString) |
| Goroutine | A lightweight execution thread managed by the Go runtime, launched via go |
| GOROOT | The root directory where Go is installed, containing the standard library in src |
Next steps
Reading code is a lot like learning a spoken language: at first, you decipher isolated words, and with practice, you effortlessly parse entire paragraphs. Here are three practical challenges to tackle next:
- Read
bufio.Scanner. - Implement a custom
io.Readerfor a practical use case (a line counter, a filtering stream, etc.). - Revisit the concurrent URL checker with fresh eyes: you can now dive deep into
http.Get,context, andsync.WaitGroup.
Appendix: solutions
Attempt each exercise before looking here. There is often more than one valid approach.
Section 1: HasPrefix
strings.HasPrefix simply delegates to stringslite.HasPrefix in the internal internal/stringslite package, where the comparison actually occurs:
func HasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
}
It first verifies that s is at least as long as prefix, and then slices and compares the leading bytes.
Section 2: ErrorEdad
type ErrorEdad struct{ Edad int }
func (e ErrorEdad) Error() string {
return fmt.Sprintf("edad inválida: %d", e.Edad)
}
func validar(edad int) error {
if edad < 0 {
return ErrorEdad{edad}
}
return nil
}
func main() {
err := validar(-5)
var ee ErrorEdad
if errors.As(err, &ee) {
fmt.Println("error de edad:", ee.Edad, "-", err)
}
}
Output: error de edad: -5 - edad inválida: -5 (or translated equivalent).errors.As inspects err looking for a value assignable to ErrorEdad; if found, it populates ee.
Section 3: Mayusculas (Uppercase Reader)
type Mayusculas struct{ r io.Reader }
func (m Mayusculas) Read(p []byte) (int, error) {
n, err := m.r.Read(p)
for i := 0; i < n; i++ {
if p[i] >= 'a' && p[i] <= 'z' {
p[i] -= 'a' - 'A'
}
}
return n, err
}
Running io.Copy(os.Stdout, Mayusculas{strings.NewReader("hola desde go\n")}) prints HOLA DESDE GO.
Notice that we return n and err untouched directly from the wrapped reader: this ensures io.EOF reaches io.Copy transparently.
An interesting bonus: in the Contador (byte counter) example, strings.Reader provides its own WriteTo implementation, so io.Copy invokes it directly and bypasses the 32 KB buffer loop altogether.
Section 4: slices
- After 5
appendcalls on an empty slice, the capacity is 8: growth steps through 1 → 2 → 4 → 8, as the 5th element forces a resize from 4 to 8. - With
b := a[:2:2], the capacity ofbis explicitly capped at 2. Consequently,appendno longer fits in the shared array, forcing Go to allocate a new one.aremains untouched as[1 2 3 4], whilebbecomes[1 2 99].
Section 5: OnceValue
valor := sync.OnceValue(func() int {
fmt.Println("calculando...")
return 42
})
fmt.Println(valor(), valor())
Output:
calculando...
42 42
The initialization closure runs on the first call to valor(), while the second call simply returns the cached result.