home blog portfolio Ian Fisher

Go

A programming language designed at Google and released in 2009. Statically typed, compiled, and garbage collected. Known for its pugnacious approach to language design and strong support for concurrency using green threads called goroutines and synchronized queues called channels.

Cheatsheet

Goroutines and channels

// buffer of 100 elements
ch := make(chan int, 100)

x, ok := <-ch // blocks if nothing to read
ch <- x // blocks until read (if unbuffered) or if buffer is full

// non-blocking read
select {
case x, ok := <-ch:
    // ...
default:
    // ...
}

// non-blocking write
select {
case ch <- x:
    // ...
case <-context.Done():
    return
default:
    // ...
}

// wait for goroutines to finish
var wg sync.WaitGroup

wg.Add(1) // outside the goroutine!
go func() {
    defer wg.Done()
    ...
}

wg.Wait()

Cancel a goroutine

doneChannel := make(chan struct{})
go func() {
    time.Sleep(1 * time.Minute)
    close(doneChannel)
}()

go func() {
    for {
        // ...
        select {
        case <-doneChannel:
            return
        default:
            continue
        }
    }
}()

Loops

for my_condition { ... }
for i := 0 ; i < n; i++ { ... }
for i, x := range xs { ... }

Type assertions and switches

s, ok := x.(string)

switch t := x.(type) {
case T1:
    // `t` is value of type `T1`
case T2:
    // `t` is value of type `T2`
default:
    // ...
}

Package organization

Commands

Be careful

Posts

Bibliography

Reference and overview:

Programming practices:

Tooling and operations:

Concurrency:

Language comparisons:

Language evolution:

Internals:

Commentary: