Go (programming language)/Cheat sheet
Last edited by dave on 12/02/2026, 11:46:05 UTC
Go (programming language) / Cheat sheet
Contents
The cheat sheet of Golang
A comprehensive guide to Go syntax, data structures, concurrency, and essential standard library functions.
1. Basics
Hello World
package main import "fmt" func main() { fmt.Println("Hello, World!") }
Variables & Constants
// Variable declaration var x int = 10 var y = 20 // Type inferred z := 30 // Short declaration (inside functions only) // Multiple declaration var a, b int = 1, 2 c, d := 3, 4 var ( e = 5 f = "six" ) // Constants const Pi = 3.14 const ( StatusOk = 200 StatusErr = 500 )
Basic Types
- Bool:
bool(true, false) - String:
string(immutable, UTF-8) - Signed Int:
int,int8,int16,int32(rune),int64 - Unsigned Int:
uint,uint8(byte),uint16,uint32,uint64,uintptr - Float:
float32,float64 - Complex:
complex64,complex128
Type Conversion
i := 42 f := float64(i) u := uint(f)
2. Control Structures
If / Else
if x > 10 { fmt.Println("Big") } else if x == 10 { fmt.Println("Ten") } else { fmt.Println("Small") } // Initializer syntax if err := run(); err != nil { fmt.Println(err) }
Switch
// Basic Switch (no break needed) switch os { case "darwin": fmt.Println("macOS") case "linux": fmt.Println("Linux") default: fmt.Println("Other") } // Tagless Switch (like if/else chain) t := time.Now() switch { case t.Hour() < 12: fmt.Println("Morning") case t.Hour() < 17: fmt.Println("Afternoon") default: fmt.Println("Evening") }
For Loops
Go only has for.
// Standard C-style for i := 0; i < 10; i++ { fmt.Println(i) } // While-style sum := 1 for sum < 1000 { sum += sum } // Infinite loop for { // do work break // exit loop } // Range (Slice/Map/Channel) nums := []int{2, 3, 4} for index, value := range nums { fmt.Printf("%d: %d\n", index, value) }
3. Data Structures
Arrays & Slices
// Arrays (Fixed size) var arr [5]int arr2 := [3]int{1, 2, 3} // Slices (Dynamic size) var s []int // nil slice s2 := make([]int, 5) // len=5, cap=5 s3 := make([]int, 5, 10) // len=5, cap=10 s4 := []int{1, 2, 3} // Slice Operations s = append(s, 4, 5) // Add elements sub := s[1:3] // Slicing (index 1 to 2) copy(dest, src) // Copy slices
Maps
// Declaration var m map[string]int // nil map m2 := make(map[string]int) // initialized m3 := map[string]int{ "one": 1, "two": 2, } // Operations m2["key"] = 10 val, exists := m2["key"] // Check existence delete(m2, "key") // Delete key
Structs
type Person struct { Name string Age int } // Initialization p1 := Person{Name: "Alice", Age: 30} p2 := Person{"Bob", 25} p3 := &Person{Name: "Charlie"} // Pointer to struct // Access fmt.Println(p1.Name)
4. Functions & Pointers
Functions
func add(x int, y int) int { return x + y } // Multiple return values func swap(x, y string) (string, string) { return y, x } // Named return values func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return // Naked return } // Variadic functions func sum(nums ...int) { // nums is a slice []int }
Pointers
i, j := 42, 2701 p := &i // point to i *p = 21 // set i through the pointer i = *p // read i through the pointer
5. Methods & Interfaces
Methods
Receivers can be value or pointer.
type Rect struct { width, height int } // Value receiver (does not modify original) func (r Rect) Area() int { return r.width * r.height } // Pointer receiver (can modify original) func (r *Rect) Scale(f int) { r.width = r.width * f r.height = r.height * f }
Interfaces
type Shape interface { Area() float64 } // Implicit implementation type Circle struct { r float64 } func (c Circle) Area() float64 { return 3.14 * c.r * c.r } // Type Assertion var i interface{} = "hello" s, ok := i.(string) // Check if i is string // Type Switch switch v := i.(type) { case int: fmt.Printf("Integer: %v", v) case string: fmt.Printf("String: %v", v) default: fmt.Printf("Unknown type") }
6. Concurrency
Goroutines
go func() { fmt.Println("Running in background") }()
Channels
// Unbuffered channel ch := make(chan int) // Buffered channel chBuff := make(chan int, 100) // Send / Receive ch <- 1 // Send to channel val := <-ch // Receive from channel // Closing close(ch) // Range over channel for val := range ch { fmt.Println(val) }
Select
Wait on multiple channel operations.
select { case msg1 := <-c1: fmt.Println("Received", msg1) case c2 <- "hello": fmt.Println("Sent hello") default: fmt.Println("Non-blocking") }
WaitGroup
import "sync" var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go func(id int) { defer wg.Done() fmt.Printf("Worker %d\n", id) }(i) } wg.Wait()
7. Error Handling
Basics
func doSomething() (int, error) { return 0, errors.New("something went wrong") } if val, err := doSomething(); err != nil { // Handle error log.Fatal(err) }
Custom Errors
type MyError struct { Msg string Code int } func (e *MyError) Error() string { return fmt.Sprintf("%d: %s", e.Code, e.Msg) }
Defer, Panic, Recover
// Defer: Executed LIFO at end of function func main() { defer fmt.Println("world") fmt.Println("hello") } // Panic & Recover func safe() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from:", r) } }() panic("oops") }
8. Packages & Testing
Package Management (Go Modules)
go mod init <module-name>: Initialize modulego mod tidy: Add missing/remove unused dependenciesgo get <package>: Download dependency
Visibility
- Capitalized: Exported (Public) ->
func Exported() - Lowercase: Unexported (Private) ->
func internal()
Testing
File must end in _test.go.
import "testing" func TestAdd(t *testing.T) { got := add(1, 2) if got != 3 { t.Errorf("add(1, 2) = %d; want 3", got) } }
go test: Run testsgo test -v: Verbose outputgo test -cover: Coverage report
9. Common Standard Library
Formatting (fmt)
Print,Println: Standard outputPrintf: Formatted output (%sstring,%dint,%vvalue,%Ttype,%+vstruct fields)Sprintf: Return formatted string
Strings (strings)
Contains,Split,Join,ToUpper,ToLower,TrimSpace
JSON (encoding/json)
type User struct { ID int `json:"id"` Name string `json:"name,omitempty"` } // Marshal (Struct -> JSON) b, err := json.Marshal(user) // Unmarshal (JSON -> Struct) err := json.Unmarshal(jsonBytes, &user)
Context (context)
Used for timeouts, cancellation, and scoping values.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() select { case <-time.After(3 * time.Second): fmt.Println("finished") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" }
Backlinks (3)
- General
- User
No backlinks yet.
- Redirects
No backlinks yet.
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'Go (programming language)/Cheat sheet' article →
No comments yet. Be the first to comment!