Go
Basics
package main—Executable 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 = 5—Explicit declaration
x := 5—Short declaration
const PI = 3.14—Constant
Data Types
int / int64—Integer types
float64 / float32—Floating point
string—UTF-8 string
bool—true or false
byte—Alias for uint8
rune—Unicode code point
[]int—Slice (dynamic array)
[5]int—Fixed-size array
map[string]int—Hash map
struct { }—Composite type
interface { }—Interface type
*int—Pointer type
Functions
func fn(a int, b int) int—Function 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"] = val—Set 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.X—Access field
type Reader interface { Read() }—Define interface
Implicit implementation—No "implements" keyword
type MyErr struct { msg string }—Custom error type
func (e *MyErr) Error() string—Implement 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 <- val—Send to channel
val := <- ch—Receive from channel
make(chan int, 10)—Buffered channel
close(ch)—Close channel
sync.WaitGroup—Wait for goroutines
sync.Mutex—Mutual exclusion lock
allprintabledoc.com