learn-go-101.html_
go.dev ↗

32 topics · 8 parts · written for people who already code

Learn Go 101

A complete tour of Go, basic to advanced, for programmers who already think in TypeScript. No "what is a variable" filler. Just what's actually different, what's the same, and where Go will surprise you.

learn-go-101, zsh

32topics
8parts
90+runnable examples
0"what is a for loop" sections

curriculum

part_01 · getting_started

01 Coming From TypeScript

You don't need a "what is a variable" tour. You need a map from what you already know to what's different. Keep this table open in another tab for the next hour, everything below builds on it.

ConceptTypeScriptGo
Package managernpm / pnpm / yarngo mod, no separate tool
Manifest filepackage.jsongo.mod
Lockfilepackage-lock.jsongo.sum
Run a filets-node file.tsgo run file.go
Buildtsc → JS + a runtimego build → one static binary
FormatterPrettier, configurablegofmt, not configurable, built in
"No value"undefined, nullzero values, nil
Async workPromise, async/awaitgoroutines + channels
Error handlingtry/catch/throwerrors are ordinary return values
Interfacesstructural, optionally declaredalways structural, always implicit
Genericsfunction f<T>(x: T)func f[T any](x T)
Classesclass + extendsno classes, struct + composition
Visibilitypublic/private/exportCapitalized = exported, that's it
Object passingalways by referenceby value, unless you pass a pointer
Registrynpmjs.comany Git host + pkg.go.dev as a mirror
FROM TYPESCRIPT

The single biggest mental shift isn't syntax, it's this: Go values are copied by default. In TS, passing an object around always passes a reference to the same object. In Go, passing a struct passes a brand-new copy, unless you explicitly pass a pointer. This trips up every JS/TS developer at least once. We'll hit it hard in the Pointers section.

One more framing that helps: TypeScript's structural typing, where a shape "just works" if it has the right fields, is basically how all of Go's typing works, all the time, including interfaces. If you've ever appreciated that TS lets you pass a plain object where an interface is expected without writing implements, you already understand half of Go's type system.

part_01 · getting_started

02 Why Go?

Go (2009, Google, Robert Griesemer, Rob Pike, Ken Thompson) was designed as a reaction to slow builds, unclear dependencies, and languages that let you write the same thing five different ways. The design goals were almost boringly practical: compile fast, run fast, make concurrency a first-class citizen, and keep the language small enough that one person can hold the whole spec in their head.

Concretely, coming from Node/TypeScript, here's what actually changes day to day:

  • Compiled, not interpreted. go build produces a single static binary. No runtime to install on the server, no node_modules to ship, no "works on my machine" version drift.
  • Real concurrency, not just async I/O. Node's event loop is single-threaded, async/await is concurrency around I/O, not parallel execution. Go's goroutines are scheduled across real OS threads. More on this in Part VI.
  • One formatter, zero debates. gofmt is not configurable. Every Go codebase you'll ever read is formatted identically. This sounds small until you've spent an hour in a tabs-vs-spaces PR review.
  • A batteries-included standard library. HTTP servers, JSON, crypto, testing, all in the box. A lot of what you'd reach for npm to solve, Go just ships.
  • Static typing with no any escape hatch. Go has any as an alias for the empty interface, but unlike TS's any, you cannot call methods or do arithmetic on it without an explicit type assertion first. The compiler never lets you quietly forget what something is.

This combination is why Go ended up as the default choice for infrastructure and CLI tooling: Docker, Kubernetes, Terraform, Prometheus, CockroachDB, and a long list of security and networking tools (Nuclei, ffuf, Caddy) are all written in Go. If you've ever run a static binary that "just worked" with no runtime installed, there's a good chance it was Go.

IDIOMATIC GO

Go's own team describes the language as intentionally boring. There's usually exactly one obvious way to do something, and the language resists adding features that would create a second way. Once you stop looking for "the clever solution," Go gets a lot more comfortable.

part_01 · getting_started

03 Install & Tooling

Grab the current stable release from go.dev/dl (Go 1.26 at the time of writing, the toolchain manages minor upgrades for you per-module). Verify with:

$ terminal
go version
# go version go1.26.2 darwin/arm64

The whole toolchain lives behind the single go command, no separate linter, bundler, or test runner to install:

CommandDoesnpm/tsc equivalent
go run main.goCompile + execute, no artifact left behindts-node main.ts
go buildProduce a binarytsc
go installBuild + put the binary on your PATHnpm install -g
go fmtReformat source in placeprettier --write
go vetCatch suspicious code the compiler allowseslint (partially)
go mod initStart a new modulenpm init
go mod tidyAdd missing deps, drop unused onesnpm install + npm prune
go get pkgAdd a dependencynpm install pkg
go test ./...Run all testsjest
go doc fmt.SprintfRead docs in the terminalctrl-clicking into .d.ts

For an editor, VS Code with the official Go extension (which installs gopls, the language server) gets you autocomplete, inline errors, format-on-save, and jump-to-definition, the same experience you're used to from the TS extension.

GOTCHA

You'll see older tutorials mention GOPATH, a single global workspace every Go project used to live inside. Ignore it. Go Modules (the go.mod file, default since Go 1.16) replaced that entirely; your project can live anywhere on disk, same as a Node project.

part_01 · getting_started

04 Your First Program

Every executable Go file starts with a package declaration and, for the entry point, a func main(), there's no implicit top-level execution like a Node script has.

● main.go
package main // every file belongs to a package; main is special

import "fmt" // fmt is stdlib, no install step

func main() { // the entry point, must be exactly this signature
	fmt.Println("Hello, Go")
}
$ go run main.go
Hello, Go

A few structural things worth noting immediately, since they differ from a TS entry file:

  • Every file declares a package. Files in the same directory must share a package name, it's effectively your module boundary, not a per-file concept like a TS module.
  • Unused imports and unused local variables are compile errors, not lint warnings. Go treats "dead code" as a correctness problem, not a style nit.
  • Braces are mandatory, placement is not optional. The opening brace must be on the same line as the declaration, gofmt enforces this, so it stops being a decision you make.
  • Comments are // and /* */, same as TS. A comment directly above a top-level declaration is a doc comment and shows up in go doc and pkg.go.dev, Go's rough equivalent of JSDoc, with no special syntax required.

To run it: go run main.go compiles to a temp binary and executes it in one step, your ts-node equivalent for quick iteration. When you're ready to ship, go build gives you a real binary you can hand to anyone, no runtime required.

part_02 · language_basics

05 Variables & Constants

Three ways to declare a variable, and only one of them (:=) will feel like your daily driver:

● main.go
var name string            // zero value: ""
var age int                 // zero value: 0
var ready bool               // zero value: false
var score float64 = 99.5     // explicit type + value
count := 0                    // short declaration, infers int; only valid inside a function
name, ok := "Ada", true      // multiple assignment, mixed types in one line

:= is scoped to the block it's declared in, same as let. There's no var-style hoisting and no temporal dead zone to worry about, but there is shadowing: an inner := with the same name creates a *new* variable rather than reassigning the outer one, which occasionally bites people coming from block-scoped let.

FROM TYPESCRIPT

There's no undefined. Every declared variable gets a concrete zero value immediately: 0 for numbers, "" for strings, false for bools, nil for pointers/slices/maps/channels/funcs/interfaces. A variable is never "not yet a thing", it's always at least its zero value.

Constants use const and must be computable at compile time, no calling functions. Go's killer feature here is untyped constants: a bare const Pi = 3.14159 has no fixed type until it's used, so it can slot into an int, float64, or anything numeric without a cast. The classic use of const is iota, Go's answer to TypeScript's enum:

● weekday.go
type Weekday int

const (
	Sunday Weekday = iota // 0, iota starts at 0 and increments each line
	Monday                 // 1
	Tuesday                 // 2
	Wednesday               // 3
	Thursday                // 4
	Friday                  // 5
	Saturday                // 6
)

fmt.Println(Wednesday) // 3, prints the underlying int unless you add a String() method
IDIOMATIC GO

Go has no real enum keyword, iota plus a named type is the idiom. Give the type a String() method (covered in Methods & Receivers) and fmt.Println will print "Wednesday" instead of 3 automatically.

part_02 · language_basics

06 Basic Types & Conversion

Go's primitive set is bigger than TypeScript's because it exposes actual machine widths instead of collapsing everything into number:

CategoryTypesTS equivalent
Booleanboolboolean
Signed intsint, int8, int16, int32, int64number (one size fits all)
Unsigned intsuint, uint8, uint16, uint32, uint64no equivalent
Floatsfloat32, float64number
Textstring (immutable UTF-8 bytes)string (UTF-16 code units)
Bytebyte, alias for uint8no equivalent
Runerune, alias for int32, one Unicode code pointno equivalent

Unlike JS's happy-to-coerce arithmetic, Go never converts types for you, not even between its own numeric types:

● convert.go
var i int = 42
var f float64 = float64(i) // explicit conversion, always
var u uint = uint(f)

// var bad float64 = i
// compile error: cannot use i (variable of type int) as float64 value
GOTCHA

"1" + 1 is a compile error in Go, full stop, there's no implicit coercion path at all, not even the "helpful" kind. For string ↔ number conversions you reach for strconv:

● strconv.go
n, err := strconv.Atoi("42")             // string → int
s := strconv.Itoa(42)                     // int → string
f, err := strconv.ParseFloat("3.14", 64)  // string → float64
// every strconv function returns an error as its second value, see Part V

Strings deserve a second look: they're immutable byte slices, not UTF-16 like JS strings. len() counts bytes, not characters, and ranging over a string yields runes (decoded Unicode code points), not bytes:

● strings.go
s := "héllo"
fmt.Println(len(s)) // 6, "é" takes 2 bytes in UTF-8, so byte length ≠ letter count

for i, r := range s {
	fmt.Printf("%d: %c\n", i, r) // i is the *byte* offset; r is the decoded rune
}

part_02 · language_basics

07 Control Flow

if works as you'd expect, with one addition: an optional init statement before the condition, scoped to the if/else chain. It's everywhere in idiomatic Go, almost always paired with error checks:

● ifs.go
if err := doThing(); err != nil {
	return err
}
// err only exists inside this if/else, it doesn't leak into the surrounding scope

Parentheses around the condition are forbidden (not just optional), and braces are mandatory, no single-line if without them. for is the only loop keyword in Go; it absorbs what TS spreads across for, while, do...while, and for...of:

● loops.go
for i := 0; i < 10; i++ { }     // classic three-part
for count < 10 { }               // while-style, same keyword, no "while"
for { }                            // infinite, break to exit
for i, v := range items { }       // range, the idiomatic default for iteration

switch is where Go actively breaks from JS habits: cases don't fall through by default. Each case exits automatically unless you explicitly write fallthrough. A conditionless switch is also a common, idiomatic replacement for long if/else if chains:

● switch.go
switch day {
case "Sat", "Sun":
	fmt.Println("weekend")
case "Mon":
	fmt.Println("ugh")
default:
	fmt.Println("weekday")
}
// no fallthrough needed between cases, the opposite of JS's default behavior

switch { // no condition at all, reads like an if/else-if chain
case score >= 90:
	grade = "A"
case score >= 80:
	grade = "B"
default:
	grade = "C"
}
FROM TYPESCRIPT

If you've ever been bitten by a missing break in a JS switch, Go just... fixed that. You'll actually miss fallthrough's explicitness once you're used to it.

Both break and continue accept a label for controlling outer loops from within a nested one, the one piece of control flow that maps directly onto JS's (rarely used) labeled statements:

● labels.go
outer:
for i := 0; i < 5; i++ {
	for j := 0; j < 5; j++ {
		if j == 2 {
			continue outer // jumps straight to the next i
		}
		if i == 3 {
			break outer // exits both loops
		}
	}
}

part_02 · language_basics

08 Functions

The headline feature: Go functions can return multiple values natively, no tuple type or wrapper object required. This is the mechanism the entire error-handling idiom is built on:

● multi.go
func divmod(a, b int) (int, int) {
	return a / b, a % b
}

q, r := divmod(17, 5) // q = 3, r = 2, no destructuring syntax needed, it's just two values

Return values can also be named, which pre-declares them as zero-valued local variables and enables a bare return ("naked return") that sends back whatever they currently hold:

● named.go
func divide(a, b float64) (result float64, err error) {
	if b == 0 {
		err = errors.New("division by zero")
		return // naked return, sends back the current result and err
	}
	result = a / b
	return
}

Variadic parameters (...T) are Go's version of rest parameters, and the same ... syntax spreads a slice back out at the call site:

● variadic.go
func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

sum(1, 2, 3)          // 6
nums := []int{4, 5, 6}
sum(nums...)           // spread, same idea as sum(...nums) in TS

Functions are first-class values, and closures work exactly like you'd expect from JS, they capture surrounding variables by reference:

● closure.go
func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

next := counter()
next() // 1
next() // 2, count was captured, not copied
IDIOMATIC GO

There's no default parameter values and no function overloading, TypeScript's function f(x: number, y = 10) or multiple overload signatures don't have a direct equivalent. The idiomatic replacements are variadic parameters, a config struct, or the "functional options" pattern (a variadic list of func(*Config) closures) once you get to Structs and Methods.

part_03 · data_structures

09 Arrays & Slices

Go has two array-like types, and you'll use the second one almost exclusively. Arrays are fixed-length and the length is part of the type, [5]int and [10]int are as different as string and number. Slices are the dynamic, resizable view you actually reach for, the closest thing to a JS array.

● slices.go
var a [5]int                  // array, fixed length, rarely used directly
s := []int{1, 2, 3}            // slice literal, no length in the type
s = append(s, 4)                 // grows automatically

nums := make([]int, 3, 5)      // len=3 (3 usable zero-valued slots), cap=5 (room to grow)

A slice isn't the data, it's a small header (pointer, length, capacity) pointing at a backing array. Slicing an existing slice doesn't copy anything; it creates a new header pointing at the same backing array:

b := a[:2] → len=2, cap=5 1 2 3 _ _ a's backing array (len=3, cap=5), b shares every cell of it

That sharing is exactly where the sharpest Go gotcha lives. If a slice still has spare capacity, append writes into the existing backing array instead of allocating a new one, which means it can silently mutate a completely different slice that happens to share the same backing array:

● append_gotcha.go
a := make([]int, 3, 5)
a[0], a[1], a[2] = 1, 2, 3

b := a[:2]          // shares a's backing array, len=2, cap=5
b = append(b, 99)     // fits within capacity, so it overwrites a[2] in place!

fmt.Println(a) // [1 2 99], a changed, even though only b was touched
fmt.Println(b) // [1 2 99]
GOTCHA

The fix is the three-index slice expression a[low:high:max], which caps the resulting capacity so append is forced to allocate a fresh array instead of reusing the shared one:

● append_fixed.go
c := a[:2:2]          // max=2 means cap is also 2, no spare room left
c = append(c, 42)       // capacity exceeded → allocates a brand-new array

fmt.Println(a) // [1 2 99], untouched this time
fmt.Println(c) // [1 2 42]

Standard slicing syntax mirrors what you already know from array destructuring intuition, just with different brackets: s[1:3], s[:3], s[3:]. And to copy elements without any aliasing risk at all, use the built-in copy:

● copy.go
dst := make([]int, len(src))
n := copy(dst, src) // n is how many elements were actually copied

part_03 · data_structures

10 Maps

map[K]V is Go's hash map, think a typed Record<K, V> that's a real runtime value, not just a type-level shape. The zero value of a map is nil, and nil maps behave asymmetrically: reading is safe, writing panics.

● maps.go
var m map[string]int        // nil map
fmt.Println(m["missing"])     // 0, reading a nil map is perfectly safe
m["key"] = 1                    // panic: assignment to entry in nil map

m2 := make(map[string]int)     // make() gives you a usable, empty map
m2["a"] = 1
GOTCHA

A struct with a map field left at its zero value is a struct with a nil map. If you build structs with &MyStruct{} and forget to initialize a map field, the first write panics at runtime, the compiler won't catch it for you.

To tell "the value is the zero value" apart from "the key doesn't exist" (something obj["key"] in JS can't cleanly do either, but for different reasons), maps support a two-value form, the comma-ok idiom, which you'll see again with type assertions and channel receives:

● comma_ok.go
value, ok := m2["a"]
if !ok {
	// key genuinely doesn't exist, value would be the zero value either way
}

delete(m2, "a") // removes a key; no-op if it isn't present, never panics

for k, v := range m2 {
	fmt.Println(k, v)
}
IDIOMATIC GO

That last loop prints keys in a randomized order, on purpose, every run. This is the opposite of a JS Map or object, which preserve insertion order. Go's runtime deliberately randomizes map iteration so nobody accidentally depends on an order that was never guaranteed. If you need sorted output, sort the keys yourself first.

part_03 · data_structures

11 Structs

A struct is the closest thing Go has to a TS interface shape, except it's not just a type annotation, it's a real, concrete value type with actual memory layout. There's no runtime "object" underneath it the way every TS object is secretly a hash map under the hood.

● structs.go
type Point struct {
	X, Y int
}

p1 := Point{X: 1, Y: 2}   // named fields, preferred; order-independent, refactor-safe
p2 := Point{1, 2}          // positional, order-dependent, breaks silently if fields are reordered

fmt.Println(p1 == p2) // true, structs compare equal if every field does

Structs nest by value, not by reference, a field of struct type embeds the whole thing inline, not a pointer to it elsewhere:

● nested.go
type Address struct {
	City, Country string
}

type Person struct {
	Name    string
	Address Address // the full Address struct lives inside Person, not a pointer to one
}

// one-off shape with no named type, occasionally handy for scratch config
config := struct {
	Debug bool
	Port  int
}{Debug: true, Port: 8080}
FROM TYPESCRIPT

A TS interface Point { x: number; y: number } only describes a shape, any object matching it works. A Go struct both describes and creates that shape: it's a concrete type you instantiate, copy, and compare, closer to a TS class with only public fields and no methods (methods get attached separately, next section).

part_03 · data_structures

12 Pointers

This is the concept TypeScript never made you learn, because JS objects are always implicitly passed by reference. Go doesn't do that, everything is passed by value by default, including structs. A pointer is how you opt into reference semantics on purpose.

● basics.go
x := 42
p := &x          // p is a *int, it holds x's memory address
*p = 100           // dereference p to write through it
fmt.Println(x)      // 100, x itself changed

var np *int          // nil pointer, the zero value of any pointer type
// *np                // panics: nil pointer dereference

Watch what happens to a struct passed with and without a pointer:

● value_vs_pointer.go
type Counter struct{ count int }

func increment(c Counter) { // value receiver, c is a full, independent copy
	c.count++
}

func incrementPtr(c *Counter) { // pointer, same underlying struct as the caller's
	c.count++
}

func main() {
	c := Counter{}
	increment(c)
	fmt.Println(c.count) // 0, the copy was incremented, not c itself

	incrementPtr(&c)
	fmt.Println(c.count) // 1, this one actually mutated c
}
FROM TYPESCRIPT

In JS/TS, function increment(c) { c.count++ } would always mutate the caller's object, there's no "pass by value" option for objects at all. Go makes that choice explicit and visible at every call site: no pointer in the signature means no mutation, guaranteed by the compiler, not just convention.

A couple of practical notes: new(T) allocates a zeroed value of type T and returns a pointer to it, a lower-level alternative to a struct literal's &T{}. And a *T that can be nil is Go's closest analog to a nullable T | undefined in TS:

● nullable.go
func findUser(id int) *User {
	if id == 0 {
		return nil // like returning undefined
	}
	return &User{ID: id}
}

if u := findUser(0); u != nil {
	fmt.Println(u.Name)
}

Rule of thumb for when to reach for a pointer: you need the function to mutate the original, the struct is large enough that copying it is wasteful, or you need a "this might not exist" nullable value. Otherwise, plain values are simpler and Go idioms lean toward them.

part_04 · methods_interfaces_generics

13 Methods & Receivers

Go has no classes, but types can still have methods, they're just declared separately from the type itself, attached via a receiver argument before the function name:

● methods.go
type Point struct{ X, Y int }

func (p Point) String() string {                 // value receiver, read-only
	return fmt.Sprintf("(%d, %d)", p.X, p.Y)
}

func (p *Point) Scale(factor int) {                // pointer receiver, mutates
	p.X *= factor
	p.Y *= factor
}

pt := Point{X: 2, Y: 3}
fmt.Println(pt)   // (2, 3), fmt calls String() automatically when it's present
pt.Scale(10)        // Go silently takes &pt here, no manual address-of needed
fmt.Println(pt)   // (20, 30)

The rule of thumb: if the method needs to mutate the receiver, or the struct is large enough that copying it is wasteful, use a pointer receiver. Otherwise a value receiver is simpler. Mixing both on the same type works but is a style smell, pick one and apply it to every method on that type.

IDIOMATIC GO

That auto-&pt conversion only works because pt is an addressable local variable. It quietly fails for values that aren't addressable, a map value, for instance, which is one of the few places a value/pointer receiver mismatch shows up as a compile error instead of just working.

Methods aren't limited to structs, any named type in your package can have them, which gives you a clean way to attach behavior to a primitive without wrapping it in a class:

● celsius.go
type Celsius float64

func (c Celsius) Fahrenheit() float64 {
	return float64(c)*9/5 + 32
}

boiling := Celsius(100)
fmt.Println(boiling.Fahrenheit()) // 212

part_04 · methods_interfaces_generics

14 Interfaces

Here's the good news: you already understand this. Go interfaces are satisfied implicitly, a type satisfies an interface just by having the right methods, with no implements keyword anywhere. That's exactly how TypeScript's structural typing already works for object shapes; Go simply applies the same idea to behavior, everywhere, all the time.

● interfaces.go
type Shape interface {
	Area() float64
}

type Rectangle struct{ Width, Height float64 }

func (r Rectangle) Area() float64 { return r.Width * r.Height }
// Rectangle satisfies Shape automatically, nothing links them explicitly

func printArea(s Shape) {
	fmt.Println(s.Area())
}

printArea(Rectangle{Width: 3, Height: 4}) // 12

The empty interface, spelled any (an alias for interface{}), can hold a value of any type, but unlike TS's any, Go won't let you call a method or do arithmetic on it without proving what it actually is first, via a type assertion or type switch:

● assertions.go
var x any = 42

n, ok := x.(int)   // comma-ok form, safe, never panics
fmt.Println(n, ok)   // 42 true

// s := x.(string)  // panics, x isn't a string and we skipped the ok check

func describe(i any) string {
	switch v := i.(type) {
	case int:
		return fmt.Sprintf("int: %d", v)
	case string:
		return fmt.Sprintf("string: %q", v)
	default:
		return fmt.Sprintf("unhandled type: %T", v)
	}
}

Idiomatic Go leans on small, focused interfaces rather than big ones, the entire standard library's I/O system runs on two one-method interfaces:

● io.go
type Reader interface {
	Read(p []byte) (n int, err error)
}

type Writer interface {
	Write(p []byte) (n int, err error)
}
// files, network connections, byte buffers, HTTP bodies, all of them satisfy these

The standard advice is "accept interfaces, return structs": functions should ask for the smallest interface that does the job (easy for callers to satisfy, easy to test with a fake) and return concrete types (easy for callers to inspect and use fully).

GOTCHA

An interface value is a (type, value) pair. A non-nil interface holding a nil pointer is itself not nil, its type slot is filled, even though the value slot is nil. Returning a typed nil pointer as an error is the classic way to trip over this, and it's a real bug pattern to know about even if you don't hit it on day one.

part_04 · methods_interfaces_generics

15 Composition & Embedding

Go has no extends, no class hierarchies, no super. Instead, a struct can embed another type by including it with no field name, its fields and methods get "promoted" up, which reads a lot like inheritance but is actually delegation under the hood:

● embedding.go
type Animal struct{ Name string }

func (a Animal) Describe() string {
	return "I am " + a.Name
}

type Dog struct {
	Animal // embedded, just the type, no field name
	Breed  string
}

d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
fmt.Println(d.Describe()) // "I am Rex", promoted straight from Animal
fmt.Println(d.Name)         // "Rex", same story
FROM TYPESCRIPT

Don't let the promoted-field convenience fool you, Dog and Animal have no subtype relationship. A function that takes an Animal will reject a Dog, full stop. Embedding is closer to automatic delegation (imagine every "missing" method on Dog quietly forwarding to d.Animal) than to class Dog extends Animal.

Interfaces embed too, which is how small interfaces compose into bigger ones without repeating method signatures:

● iface_embed.go
type ReadWriter interface {
	Reader // pulls in Read(p []byte) (int, error)
	Writer // pulls in Write(p []byte) (int, error)
}
// any type with both methods satisfies ReadWriter automatically, no extra work

part_04 · methods_interfaces_generics

16 Generics

Go got generics in 1.18 (2022), and if you already write <T> in TypeScript, the concept transfers directly, only the brackets and a couple of keywords change:

FROM TYPESCRIPT

TypeScript: function map<T, U>(arr: T[], f: (x: T) => U): U[]
Go: func Map[T, U any](s []T, f func(T) U) []U

Same idea, square brackets instead of angle brackets, and every type parameter needs an explicit constraint (any here means "no constraint," not TS's escape-hatch any).

● generics.go
func Map[T, U any](s []T, f func(T) U) []U {
	result := make([]U, len(s))
	for i, v := range s {
		result[i] = f(v)
	}
	return result
}

nums := []int{1, 2, 3}
doubled := Map(nums, func(n int) int { return n * 2 })                   // [2 4 6]
strs := Map(nums, func(n int) string { return fmt.Sprintf("#%d", n) })   // [#1 #2 #3]

Constraints beyond any and comparable (which restricts to types supporting ==) are just interfaces listing which types or underlying types are allowed. The ~ prefix means "this type, or anything whose underlying type is this":

● constraints.go
type Number interface {
	~int | ~int64 | ~float64 // any type whose underlying type is one of these
}

func Sum[T Number](nums []T) T {
	var total T
	for _, n := range nums {
		total += n
	}
	return total
}

Generic types work the same way, a type parameter list right after the type name, then used throughout its methods:

● stack.go
type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(item T) {
	s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() (T, bool) {
	var zero T
	if len(s.items) == 0 {
		return zero, false // comma-ok again, same pattern as maps
	}
	item := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return item, true
}
IDIOMATIC GO

Reach for generics when you'd otherwise duplicate identical logic across types (containers, Map/Filter/Reduce helpers). For everything else, especially anything centered on behavior rather than data shape, the Go community still tends to prefer plain interfaces. Don't generic-ify by default just because you can.

part_05 · error_handling

17 Errors As Values

Go has no exceptions for ordinary failure. error is just an interface, one method, nothing magic:

● builtin
type error interface {
	Error() string
}

Because errors are ordinary values, the idiom is to check and propagate them immediately, right where they happen:

● propagate.go
func readConfig() (*Config, error) {
	data, err := os.ReadFile("config.json")
	if err != nil {
		return nil, err // propagate immediately, there's no exception waiting upstream
	}
	var cfg Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		return nil, fmt.Errorf("parsing config: %w", err)
	}
	return &cfg, nil
}
FROM TYPESCRIPT

No try/catch/throw. It reads more verbose at first, but every place a call can fail is visible right at the call site, instead of hiding behind a try block three functions up the stack that may or may not still apply.

Wrap an error with %w to add context while preserving the original for inspection, then use errors.Is to check identity against a known sentinel error:

● sentinel.go
var ErrNotFound = errors.New("not found")

func findUser(id int) (*User, error) {
	if id == 0 {
		return nil, fmt.Errorf("findUser: %w", ErrNotFound) // %w wraps, keeping identity intact
	}
	return &User{ID: id}, nil
}

_, err := findUser(0)
if errors.Is(err, ErrNotFound) {
	fmt.Println("user does not exist")
}

For errors that need to carry structured data, define a type implementing Error() string, then unwrap it with errors.As:

● custom_error.go
type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}

func validate(age int) error {
	if age < 0 {
		return &ValidationError{Field: "age", Msg: "must be non-negative"}
	}
	return nil
}

var ve *ValidationError
if errors.As(validate(-1), &ve) {
	fmt.Println("field:", ve.Field) // "field: age"
}

part_05 · error_handling

18 Defer, Panic & Recover

defer schedules a call to run right before the surrounding function returns, however it returns, including via panic. Multiple deferred calls run in LIFO order, last deferred, first executed:

● defer_order.go
func main() {
	defer fmt.Println("1")
	defer fmt.Println("2")
	defer fmt.Println("3")
	fmt.Println("main body")
}
// main body
// 3
// 2
// 1

The overwhelmingly common use is guaranteed cleanup, closing a file, unlocking a mutex, right next to the line that acquired the resource, instead of in a separate finally block far away:

● cleanup.go
f, err := os.Open("file.txt")
if err != nil {
	return err
}
defer f.Close() // runs no matter which return statement fires below
GOTCHA

A deferred call's arguments are evaluated immediately, only the call itself is delayed. defer fmt.Println("i:", i) captures whatever i is right now, not its value at the moment the function actually returns. Wrap it in a closure (defer func(){ fmt.Println("i:", i) }()) if you need the later value.

panic stops normal execution and starts unwinding the stack, running deferred calls as it goes. recover, called from inside a deferred function, stops that unwind and lets the function return normally instead:

● recover.go
func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r) // turn the panic back into a normal error
		}
	}()
	result = a / b // panics if b == 0
	return
}
IDIOMATIC GO

panic/recover is not Go's try/catch. Reach for it only at real boundaries, recovering inside an HTTP handler so one bad request doesn't crash the whole server, for instance, not as a general control-flow mechanism. Expected, recoverable failures are error values; panics are for "this should be impossible" and genuine programmer mistakes.

part_06 · concurrency

19 Goroutines

This is the part of Go that doesn't map onto anything in Node. async/await in JS is concurrency around I/O on a single thread, the event loop never runs two callbacks at literally the same instant. A goroutine is different: it's a lightweight function scheduled across real OS threads by Go's runtime (an M:N scheduler), so on a multi-core machine, goroutines can execute in genuine parallel.

● goroutine.go
func sayHello() {
	fmt.Println("hello from a goroutine")
}

func main() {
	go sayHello()               // starts running concurrently, doesn't block
	fmt.Println("hello from main")
	// main can exit before sayHello ever runs, nothing is waiting for it yet
}

Goroutines start with a tiny (≈2KB) stack that grows as needed, so spawning thousands, even millions, is normal in Go in a way that would be unthinkable with OS threads directly. The tradeoff is that real parallelism brings real data races, something JS's single-threaded model simply can't produce:

● race.go
counter := 0
for i := 0; i < 1000; i++ {
	go func() {
		counter++ // unsynchronized read-modify-write, a genuine data race
	}()
}
// counter's final value is unpredictable. Catch races with: go run -race main.go
GOTCHA

go run -race and go test -race instrument your program to detect data races at runtime. There's no reason not to run your test suite with -race on, treat it the way you'd treat a strict linter.

part_06 · concurrency

20 Channels

Channels are typed pipes goroutines use to pass values to each other safely, Go's answer to "how do concurrent things talk without stepping on each other's memory." The philosophy, in Go's own words: don't share memory to communicate, communicate to share memory.

go worker(1) sending goroutine chan int range ch receiving goroutine → →
● channels.go
ch := make(chan int)             // unbuffered, send blocks until someone receives
buffered := make(chan int, 5)      // buffered, send only blocks once full

go func() {
	ch <- 42 // send
}()
value := <-ch // receive, blocks until a value arrives
fmt.Println(value) // 42

An unbuffered send/receive pair is a real synchronization point, the sender doesn't proceed until the receiver is ready, which is what makes channels useful for coordination, not just data transfer. close signals "no more values are coming," and a range loop reads until close automatically:

● close_range.go
close(ch) // no more sends allowed after this, sending to a closed channel panics

v, ok := <-ch // ok is false once the channel is closed AND fully drained
if !ok {
	fmt.Println("channel closed")
}

for v := range ch { // reads until close, then exits the loop on its own
	fmt.Println(v)
}

Function signatures often restrict a channel to send-only or receive-only, which the compiler enforces, a nice bit of self-documentation you'll see constantly once you get to worker pools:

● directional.go
func producer(out chan<- int) { // send-only, from this function's point of view
	out <- 1
	close(out)
}

func consumer(in <-chan int) { // receive-only
	for v := range in {
		fmt.Println(v)
	}
}

part_06 · concurrency

21 The select Statement

select is a switch for channel operations, it waits on multiple sends/receives at once and proceeds with whichever is ready first. If several are ready simultaneously, one is chosen at random, on purpose, to prevent starvation.

● select.go
select {
case msg := <-ch1:
	fmt.Println("from ch1:", msg)
case msg := <-ch2:
	fmt.Println("from ch2:", msg)
case <-time.After(2 * time.Second):
	fmt.Println("timed out waiting on both channels")
default:
	fmt.Println("nothing ready right now, this makes the whole select non-blocking")
}

Without a default, select blocks until one case can proceed, the closest thing to Promise.race, though mechanically it's a language statement operating on channels rather than a one-shot combinator over promises, and it's usually written inside a loop so a goroutine can keep servicing multiple channels indefinitely.

part_06 · concurrency

22 sync: Mutexes & WaitGroups

sync.WaitGroup waits for a set of goroutines to finish, the rough equivalent of Promise.all, minus the automatic result collection; you coordinate completion, not return values:

● waitgroup.go
var wg sync.WaitGroup

for i := 0; i < 5; i++ {
	wg.Add(1)
	go func(n int) {
		defer wg.Done()
		fmt.Println("worker", n)
	}(i)
}

wg.Wait() // blocks until all 5 have called Done()
IDIOMATIC GO

That func(n int) { ... }(i) pattern, passing the loop variable in as a parameter, exists because older Go versions shared one loop variable across every iteration, so every closure saw its final value. Go 1.22 (2024) changed loops to give each iteration its own variable, so plain i is safe to capture directly today. You'll still see the parameter-passing style everywhere, since most code needs to run on older Go too.

Go 1.25 added a small convenience that folds Add/go/Done into one call:

● waitgroup_go.go
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
	wg.Go(func() { // Go 1.25+: handles Add(1) and Done() for you
		fmt.Println("worker", i)
	})
}
wg.Wait()

sync.Mutex is the tool for the other half of concurrent programming: protecting shared state, rather than orchestrating completion. JS rarely needs this, single-threaded, so if it's new to you, that's expected:

● mutex.go
type SafeCounter struct {
	mu    sync.Mutex
	count int
}

func (c *SafeCounter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock() // unlocks even if something above panics
	c.count++
}

And sync.Once guarantees a function runs exactly once, no matter how many goroutines call it, a clean way to write lazy, concurrency-safe initialization:

● once.go
var once sync.Once

func setup() {
	once.Do(func() {
		fmt.Println("runs exactly once, regardless of how many goroutines call setup()")
	})
}

A useful rule of thumb for choosing between the two tools this section covers: channels for communicating and orchestrating between goroutines, mutexes for protecting a shared piece of state that doesn't need to move anywhere.

part_06 · concurrency

23 Context & Concurrency Patterns

context.Context carries cancellation signals, deadlines, and request-scoped values across API and goroutine boundaries. It's the standard first parameter for anything that might need to be cancelled or time out, you'll see ctx context.Context as literally the first argument all over idiomatic Go code:

● context.go
func fetchWithTimeout(ctx context.Context, url string) error {
	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel() // always call cancel, even on success, to free resources

	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err // this will be context.DeadlineExceeded if the timeout fired first
	}
	defer resp.Body.Close()
	return nil
}

Putting goroutines, channels, and directional channel types together gives you the worker pool, a small number of goroutines pulling from a shared jobs channel, a pattern you'll reuse constantly once you're writing real concurrent Go:

● worker_pool.go
func worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		results <- j * 2
	}
}

func main() {
	jobs := make(chan int, 5)
	results := make(chan int, 5)

	for w := 1; w <= 3; w++ {
		go worker(w, jobs, results) // 3 workers, all pulling from the same jobs channel
	}

	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs) // workers' range loops exit once jobs is drained and closed

	for a := 1; a <= 5; a++ {
		fmt.Println(<-results)
	}
}

part_07 · stdlib_and_real_programs

24 Packages & Modules

Every Go file declares a package, and every file in the same directory must share that package name, it's your unit of code organization, roughly one level coarser than a TS module. A project's dependency graph lives in go.mod:

● go.mod
module github.com/yourname/myproject

go 1.26

require (
	github.com/gorilla/mux v1.8.1
)

There's no public, private, or export keyword. Visibility is spelled with a capital letter, full stop:

● profile.go
package user

type Profile struct {
	Name  string // capitalized → exported, visible outside this package
	email string // lowercase → unexported, package-private
}

func NewProfile(name string) *Profile { /* ... */ } // exported constructor
func validate(name string) bool { /* ... */ }          // unexported helper
FROM TYPESCRIPT

No separate keyword to remember or forget, the identifier's spelling is the access modifier. It reads strange for about a day, then you stop noticing.

One Go-specific feature with no npm equivalent: a package under a directory literally named internal/ can only be imported by code inside the module tree rooted above that internal/ directory, the compiler enforces this, not a linter rule:

● layout
myproject/
  internal/
    auth/       # importable only from within myproject
  pkg/
    utils/      # importable from anywhere

part_07 · stdlib_and_real_programs

25 Working With JSON

encoding/json is standard library, no zod, no class-transformer, nothing to install. Struct tags tell it how to map fields to JSON keys:

● json.go
type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email,omitempty"` // omitted from output entirely if it's the zero value
}

u := User{ID: 1, Name: "Ada"}
data, _ := json.Marshal(u)
fmt.Println(string(data)) // {"id":1,"name":"Ada"}

var u2 User
json.Unmarshal(data, &u2)
fmt.Println(u2.Name) // Ada
GOTCHA

Unexported fields are invisible to encoding/json, the same capitalization rule from Packages applies here. A struct field you forgot to capitalize will just silently never appear in the marshaled output, with no error.

For genuinely dynamic JSON where you don't have (or don't want) a struct, decode into map[string]any, the closest thing to TS's "parse into unknown and narrow later":

● dynamic.go
var payload map[string]any
json.Unmarshal(data, &payload)
// payload["id"] decodes as float64, JSON numbers default to float64 when the shape is unknown

part_07 · stdlib_and_real_programs

26 Files & the OS

For small files, the whole read-or-write happens in one call:

● files.go
data, err := os.ReadFile("notes.txt")           // reads the whole file into memory
err = os.WriteFile("out.txt", []byte("hi"), 0644) // 0644 is the file permission bits

For anything larger, stream it, this is also a good moment to see io.Reader in the wild, since *os.File is one of dozens of standard library types that satisfy it:

● scan.go
f, err := os.Open("large.log")
if err != nil {
	return err
}
defer f.Close()

scanner := bufio.NewScanner(f) // wraps any io.Reader with line-by-line scanning
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

Command-line args and environment variables, if you're writing a CLI tool, which, statistically, you eventually will in Go:

● env.go
args := os.Args[1:]           // os.Args[0] is the binary's own path
port := os.Getenv("PORT")       // "" if unset, os.LookupEnv gives you a comma-ok version

part_07 · stdlib_and_real_programs

27 HTTP Servers & Clients

You can ship a working API with zero dependencies, no Express required, because net/http already is one. Since Go 1.22, ServeMux patterns support HTTP methods and wildcard path segments directly:

● server.go
mux := http.NewServeMux()

mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	fmt.Fprintf(w, "user id: %s", id)
})

log.Fatal(http.ListenAndServe(":8080", mux))

There's no built-in middleware chaining like Express's app.use, instead, middleware is just a function wrapping one http.Handler in another, then you compose them yourself by nesting calls:

● middleware.go
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
	})
}

http.ListenAndServe(":8080", loggingMiddleware(mux)) // wrap, don't chain

And the client side, paired with the JSON decoding from two sections ago:

● client.go
resp, err := http.Get("https://api.example.com/users")
if err != nil {
	return err
}
defer resp.Body.Close()

var users []User
json.NewDecoder(resp.Body).Decode(&users)
IDIOMATIC GO

For anything beyond a handful of routes, most teams still reach for a router library (chi, gin, echo), the same way you'd reach for Express on top of Node's built-in http module. The standard library is a genuinely solid floor to start from, not a toy.

part_07 · stdlib_and_real_programs

28 Testing

Testing is part of the toolchain, go test, no Jest or Vitest to install. Any file ending in _test.go is a test file, and any function shaped func TestXxx(t *testing.T) is a test:

● add_test.go
func TestAdd(t *testing.T) {
	tests := []struct {
		name     string
		a, b     int
		expected int
	}{
		{"positive numbers", 2, 3, 5},
		{"negative numbers", -2, -3, -5},
		{"mixed signs", -2, 3, 1},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Add(tt.a, tt.b)
			if result != tt.expected {
				t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
			}
		})
	}
}
FROM TYPESCRIPT

No describe/it nesting and no separate assertion library baked in, t.Errorf is the whole mechanism, and a slice of struct literals is the idiomatic stand-in for Jest's test.each. This "table-driven test" shape is the single most common test pattern you'll see in real Go code.

● terminal
go test ./...          # run everything in the module
go test -run TestAdd     # run one test by name
go test -v                 # verbose, show each subtest as it runs
go test -cover              # print coverage percentage

part_08 · advanced_and_idiomatic

29 Reflection

The reflect package lets code inspect types and values it didn't know about at compile time, it's what actually powers encoding/json, fmt.Println, and struct-tag-based libraries under the hood:

● reflect.go
func describe(i any) {
	t := reflect.TypeOf(i)
	v := reflect.ValueOf(i)
	fmt.Printf("type: %v, value: %v, kind: %v\n", t, v, t.Kind())
}

describe(42)      // type: int, value: 42, kind: int
describe("hello") // type: string, value: hello, kind: string
IDIOMATIC GO

Treat reflect as a last resort in application code. It bypasses the compiler's type checking, runs slower than static code paths, and every Go style guide will tell you the same thing: reach for an interface first. Knowing it exists mostly helps you understand how libraries like encoding/json work, not something you'll write often yourself.

part_08 · advanced_and_idiomatic

30 Memory: Stack, Heap & GC

Go is garbage collected, same as JS, and worth pointing out explicitly, since it's easy to assume a compiled language must mean manual memory management like C or Rust. It doesn't. What is new is the compiler deciding, per value, whether it can live on the fast stack or needs the heap, a process called escape analysis, and it's fully automatic:

● escape.go
func createOnStack() int {
	x := 42
	return x // x is copied out, the compiler can safely keep it on the stack
}

func createOnHeap() *int {
	x := 42
	return &x // x's address escapes this function, so it must live on the heap
}

You can watch the compiler's decisions directly:

● terminal
go build -gcflags="-m" main.go
# ./main.go:8:2: moved to heap: x

The value-vs-reference distinction from Pointers, generalized, this table is worth bookmarking:

Copied by valueShare underlying data
int, float64, bool, stringslice, map, chan
array (fixed-size)func
structpointer, interface
IDIOMATIC GO

The garbage collector itself keeps improving under the hood, Go 1.26 turned on the new "Green Tea" collector by default, which reduces GC overhead noticeably for allocation-heavy workloads. You never touch this directly; it's the same story as V8's GC getting faster underneath your Node code with each release.

part_08 · advanced_and_idiomatic

31 Idiomatic Go & Project Layout

A short list of conventions that separate Go code that reads like Go from Go code that reads like translated TypeScript:

  • Run gofmt, always. It's not configurable, which is the point, every Go codebase on earth is formatted the same way, so code review never wastes time on style.
  • Short names in short scopes. i for a loop index, err for an error, r/w for an HTTP request/writer. Descriptive names are for things with wide scope, not everything.
  • MixedCaps, never snake_case. Including for constants, no SCREAMING_SNAKE_CASE.
  • Package names are short, lowercase, no underscores, http, json, bufio, never my_utils.
  • Accept interfaces, return structs. Ask callers for the smallest interface that does the job; hand callers back a concrete type they can fully inspect.
  • Check every error where it happens. Resist the urge to bubble everything up unchecked with _, a discarded error is a decision, make it on purpose.

For project structure, there's no framework-enforced layout the way Nest or Angular impose one, but a de facto community convention has emerged for anything bigger than a single file:

● layout
myapp/
  cmd/
    myapp/
      main.go        # thin entry point, wires things together, no real logic
  internal/
    server/            # HTTP handlers
    store/               # data access
  go.mod
  go.sum

cmd/ holds thin entry points, internal/ holds everything that isn't meant to be imported by other projects (enforced by the compiler, as covered in Packages), and business logic lives in plain, well-named packages rather than deeply nested folders.

part_08 · advanced_and_idiomatic

32 Where To Go Next

You now have real coverage of the language, what's left is mileage. A few genuinely good next stops:

  • tour.go.dev, the official interactive tour, good for drilling syntax with instant feedback.
  • Effective Go, the closest thing Go has to a style bible, written by the language's own creators.
  • pkg.go.dev, documentation for the standard library and any public module, generated straight from doc comments.

For a first real project, pick something that forces you through goroutines, channels, and error handling in the same afternoon, a concurrent port scanner, a CLI that hits a handful of APIs in parallel and merges the results, or a small proxy that logs and forwards requests. All three are small enough to finish, and none of them are "print hello world" easy.