Go

Basics

package mainExecutable package
import "fmt"Import package
func main() { }Entry point
fmt.Println("Hello")Print with newline
fmt.Printf("%s %d", s, n)Formatted print
fmt.Sprintf()Format to string
var x int = 5Explicit declaration
x := 5Short declaration
const PI = 3.14Constant

Data Types

int / int64Integer types
float64 / float32Floating point
stringUTF-8 string
booltrue or false
byteAlias for uint8
runeUnicode code point
[]intSlice (dynamic array)
[5]intFixed-size array
map[string]intHash map
struct { }Composite type
interface { }Interface type
*intPointer type

Functions

func fn(a int, b int) intFunction with return
func fn(a, b int) (int, error)Multiple returns
val, err := fn()Capture multi-return
func (r Recv) method()Method on type
func fn(args ...int)Variadic function
fn := func(x int) int { }Anonymous function
defer fn()Execute on function exit
go fn()Launch goroutine

Slices & Maps

s := []int{1, 2, 3}Create slice
make([]int, len, cap)Make slice with capacity
append(s, 4, 5)Append elements
s[1:3]Slice of slice
len(s) / cap(s)Length / capacity
copy(dst, src)Copy slice
m := map[string]int{}Create map
make(map[string]int)Make map
m["key"] = valSet map value
val, ok := m["key"]Get with exists check
delete(m, "key")Delete from map

Structs & Interfaces

type Point struct { X, Y int }Define struct
p := Point{X: 1, Y: 2}Create struct
p.XAccess field
type Reader interface { Read() }Define interface
Implicit implementationNo "implements" keyword
type MyErr struct { msg string }Custom error type
func (e *MyErr) Error() stringImplement error interface
type Embed struct { Base }Struct embedding

Control Flow

if cond { } else { }If-else
if val := fn(); val > 0 { }If with init statement
switch val { case 1: }Switch (no fallthrough)
for i := 0; i < n; i++ { }Classic for loop
for i, v := range slice { }Range over slice
for k, v := range myMap { }Range over map
for { }Infinite loop (like while)
select { case <- ch: }Channel select

Error Handling

if err != nil { return err }Check and propagate
errors.New("message")Create error
fmt.Errorf("wrap: %w", err)Wrap error
errors.Is(err, target)Check error type
errors.As(err, &target)Extract error type
panic("msg")Unrecoverable error
recover()Recover from panic

Concurrency

go func() { }()Launch goroutine
ch := make(chan int)Create channel
ch <- valSend to channel
val := <- chReceive from channel
make(chan int, 10)Buffered channel
close(ch)Close channel
sync.WaitGroupWait for goroutines
sync.MutexMutual exclusion lock
allprintabledoc.com