Quick reference for Go basics — structures, functions, loops, and goroutines.
| Structure | Syntax | Notes |
|---|---|---|
| Slice | []int{1, 2, 3} |
Dynamic length |
| Map | map[string]int{"a": 1} |
Key-value |
| Array | [3]int{1, 2, 3} |
Fixed length |
| Struct | struct{ Name string } |
Custom type |
// Basic function
func greet(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
// Multiple return values
func divmod(a, b int) (int, int) {
return a / b, a % b
}
// Variadic
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function as value
square := func(x int) int { return x * x }
// for (the only loop)
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// range over slice
for i, v := range []int{1, 2, 3} {
fmt.Println(i, v)
}
// range over map
for k, v := range map[string]int{"a": 1} {
fmt.Println(k, v)
}
// while-like
n := 0
for n < 5 {
n++
}
// Goroutines
go func() {
fmt.Println("running concurrently")
}()
// Channels
ch := make(chan int, 2)
ch <- 42
val := <-ch
// WaitGroup
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d\n", id)
}(i)
}
wg.Wait()
// select (multiplex channels)
select {
case msg := <-ch1:
fmt.Println(msg)
case msg := <-ch2:
fmt.Println(msg)
case <-time.After(time.Second):
fmt.Println("timeout")
}
// Mutex
var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()