home blog portfolio Ian Fisher

Go cheatsheet

See also: wiki/golang

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 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

Be careful

Commands