Go (Golang) Language Cheat Sheet
Quick reference guide for Go: Structs, interfaces, goroutines, channels, slices, maps, and standard CLI commands.
Languages
golang
go
backend
Go (Golang) is an open-source programming language designed at Google for building simple, fast, and reliable software with strong built-in concurrency support.
Variables, Types & Control Flow
go
package main
import "fmt"
func main() {
// Short variable declaration (type inferred)
name := "Alice"
age := 30
// Explicit variable declaration
var score float64 = 95.5
// If-statement with short initialization
if val := age * 2; val > 50 {
fmt.Printf("%s is mature (%d)\n", name, score)
}
// For loop (Go's only loop construct)
for i := 0; i < 3; i++ {
fmt.Println("Index:", i)
}
}
Structs & Interfaces
Go uses structural typing via Interfaces without explicit implements keywords.
go
type Stringer interface {
String() string
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Method receiver (implements Stringer implicitly)
func (u User) String() string {
return fmt.Sprintf("User #%d: %s", u.ID, u.Name)
}
Slices & Maps Operations
Table
| Operation | Code Snippet | Purpose |
|---|---|---|
| Create Slice | s := make([]string, 0, 10) | Make slice with length 0, capacity 10 |
| Append Slice | s = append(s, "item1", "item2") | Append elements dynamically |
| Slice Sub-range | sub := s[1:3] | Slice range from index 1 to 2 |
| Create Map | m := make(map[string]int) | Initialize key-value map |
| Check Map Key | val, ok := m["key"] | Safe key presence lookup (ok == true) |
| Delete Map Key | delete(m, "key") | Remove key-value entry from map |
Concurrency: Goroutines & Channels
Goroutines are lightweight threads managed by the Go runtime. Channels enable safe communication between goroutines.
go
func fetchWorker(id int, ch chan<- string) {
// Send data to channel
ch <- fmt.Sprintf("Worker %d finished", id)
}
func main() {
ch := make(chan string, 2) // Buffered channel
go fetchWorker(1, ch)
go fetchWorker(2, ch)
// Receive data from channel
msg1 := <-ch
msg2 := <-ch
fmt.Println(msg1)
fmt.Println(msg2)
}
Select & Timeout Pattern
go
select {
case msg := <-ch:
fmt.Println("Received:", msg)
case <-time.After(2 * time.Second):
fmt.Println("Operation timed out")
}
Essential `go` Tool Commands
Table
| Command | Action |
|---|---|
go mod init module-name | Initialize a new go.mod file |
go run main.go | Compile and run Go program |
go test ./... | Run unit tests across all sub-packages |
go build -o app | Compile binary output executable app |
go get package@latest | Add dependency to go.mod & go.sum |
go fmt ./... | Format Go source code according to standard style |
Common Pitfalls & Tips
[!WARNING] In Go, sending to or receiving from an uninitialized
nilchannel blocks forever and causes a fatal runtime deadlock! Always initialize channels withmake(chan T).
[!TIP] Always check and handle returned errors explicitly:
if err != nil { return err }.