AI Generate Go docs instantly

Go Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with Go basics

Hello World

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

Comments

// Single line comment
/* Multi-line
   comment */

User Input

var name string
fmt.Scanln(&name)

Type Conversion

strconv.Atoi("42")     // string to int
strconv.Itoa(42)       // int to string
float64(intValue)

Run & Build

go run main.go   // Run
go build         // Compile
go mod init app  // Init module

Variables & Data Types

7 snippets

Store and manage data in Go

Var

var name string = "John"

Short Declaration

age := 25

Const

const PI = 3.14159

Array

var nums [5]int = [5]int{1, 2, 3, 4, 5}

Slice

fruits := []string{"apple", "banana"}

Map

ages := map[string]int{"John": 30}

Struct

type Person struct {
    Name string
    Age  int
}

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

+ - * /    // Add, Sub, Mul, Div
%          // Modulus (remainder)
++ --      // Increment/Decrement (statement only)

Comparison

==  !=     // Equal, Not equal
>   <      // Greater, Less than
>=  <=     // Greater/Less or equal

Logical

&&   // AND
||   // OR
!    // NOT

Assignment

=   :=     // Assign, Short declare
+=  -=  *= /=  %=
&=  |=  ^=  <<= >>=

Bitwise

&   // AND
|   // OR
^   // XOR
&^  // AND NOT (bit clear)
<<  // Left shift
>>  // Right shift

Address/Pointer

&x   // Address of x
*p   // Value at pointer p
*int // Pointer to int type

Channel

<-   // Send/receive
ch <- v    // Send v to channel
v := <-ch  // Receive from channel

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

10 snippets

Repeat code efficiently with iterations

For (Classic)

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

For (While-style)

for count < 10 {
    count++
}

For (Infinite)

for {
    if done { break }
}

Range (Slice)

for i, v := range slice {
    fmt.Println(i, v)
}

Range (Map)

for key, value := range myMap {
    fmt.Println(key, value)
}

Range (String)

for i, char := range "hello" {
    fmt.Printf("%d: %c\n", i, char)
}

Ignore Index

for _, v := range slice {
    fmt.Println(v)
}

Break

for i := 0; i < 10; i++ {
    if i == 5 { break }
}

Continue

for i := 0; i < 10; i++ {
    if i == 5 { continue }
    fmt.Println(i)
}

Labeled Break

outer:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if j == 1 { break outer }
    }
}

Conditionals

5 snippets

Direct program execution with conditions

If/Else

if x > 0 {
    fmt.Println("positive")
} else if x < 0 {
    fmt.Println("negative")
} else {
    fmt.Println("zero")
}

If with Init

if err := doSomething(); err != nil {
    fmt.Println(err)
}

Switch

switch day {
case "Mon":
    fmt.Println("Monday")
case "Tue", "Wed":
    fmt.Println("Midweek")
default:
    fmt.Println("Other")
}

Switch (No Condition)

switch {
case x > 0:
    fmt.Println("positive")
case x < 0:
    fmt.Println("negative")
}

Type Switch

switch v := i.(type) {
case int:
    fmt.Println("int", v)
case string:
    fmt.Println("string", v)
}

Functions

4 snippets

Reusable blocks of code

Function

func greet(name string) string {
    return "Hello, " + name + "!"
}

Multiple Returns

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

Named Returns

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

Variadic

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

Error Handling

5 snippets

Handle errors explicitly

Error Check

result, err := doSomething()
if err != nil {
    log.Fatal(err)
}

Custom Error

errors.New("something went wrong")

Wrap Error

fmt.Errorf("failed: %w", err)

Defer

defer file.Close()

Panic/Recover

defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered:", r)
    }
}()

Concurrency

5 snippets

Goroutines and channels for parallelism

Goroutine

go doSomething()

Channel

ch := make(chan int)
ch <- 42
value := <-ch

Buffered Channel

ch := make(chan int, 100)

Select

select {
case msg := <-ch1:
    fmt.Println(msg)
case <-time.After(time.Second):
    fmt.Println("timeout")
}

WaitGroup

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    doWork()
}()
wg.Wait()

Interfaces

4 snippets

Define contracts and behaviors

Interface

type Reader interface {
    Read(p []byte) (n int, err error)
}

Implement

func (f *File) Read(p []byte) (n int, err error) {
    // implementation
}

Empty Interface

func print(v interface{}) {
    fmt.Println(v)
}

Type Assertion

str, ok := v.(string)

Generics (Go 1.18+)

5 snippets

Type parameters for flexible code

Generic Function

func Min[T ~int | ~float64](a, b T) T {
    if a < b {
        return a
    }
    return b
}

Type Constraints

type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}

Generic Struct

type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() T {
    item := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return item
}

Comparable

func Contains[T comparable](slice []T, item T) bool {
    for _, v := range slice {
        if v == item {
            return true
        }
    }
    return false
}

Multiple Type Params

func Map[T, U any](items []T, fn func(T) U) []U {
    result := make([]U, len(items))
    for i, v := range items {
        result[i] = fn(v)
    }
    return result
}

Context

5 snippets

Request-scoped values and cancellation

Background Context

ctx := context.Background()

With Timeout

ctx, cancel := context.WithTimeout(
    context.Background(),
    5*time.Second,
)
defer cancel()

With Cancel

ctx, cancel := context.WithCancel(context.Background())

go func() {
    <-ctx.Done()
    fmt.Println("cancelled")
}()

cancel()  // Trigger cancellation

With Value

type key string
ctx := context.WithValue(ctx, key("user"), "john")

// Retrieve
user := ctx.Value(key("user")).(string)

Check Done

select {
case <-ctx.Done():
    return ctx.Err()  // Canceled or DeadlineExceeded
default:
    // Continue processing
}

Testing

5 snippets

Write and run tests

Basic Test

// math_test.go
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Add(2,3) = %d; want 5", result)
    }
}

Table Driven

func TestAdd(t *testing.T) {
    tests := []struct {
        a, b, want int
    }{
        {1, 2, 3},
        {0, 0, 0},
        {-1, 1, 0},
    }

    for _, tc := range tests {
        got := Add(tc.a, tc.b)
        if got != tc.want {
            t.Errorf("Add(%d,%d) = %d; want %d",
                tc.a, tc.b, got, tc.want)
        }
    }
}

Subtests

func TestMath(t *testing.T) {
    t.Run("Add", func(t *testing.T) {
        if Add(1, 2) != 3 {
            t.Fail()
        }
    })

    t.Run("Multiply", func(t *testing.T) {
        if Multiply(2, 3) != 6 {
            t.Fail()
        }
    })
}

Benchmark

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}

Run Tests

go test           // Run all tests
go test -v        // Verbose
go test -run Add  // Run matching
go test -bench .  // Run benchmarks

HTTP

6 snippets

Build web servers and clients

Simple Server

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
})

http.ListenAndServe(":8080", nil)

Handler Interface

type Handler struct{}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello"))
}

http.Handle("/", Handler{})

GET Request

resp, err := http.Get("https://api.example.com/data")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, _ := io.ReadAll(resp.Body)

POST with JSON

data := map[string]string{"name": "John"}
jsonData, _ := json.Marshal(data)

resp, err := http.Post(
    "https://api.example.com/users",
    "application/json",
    bytes.NewBuffer(jsonData),
)

Custom Client

client := &http.Client{
    Timeout: 10 * time.Second,
}

req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer token")

resp, err := client.Do(req)

JSON Response

func handler(w http.ResponseWriter, r *http.Request) {
    data := map[string]string{"status": "ok"}

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(data)
}

More Cheat Sheets

FAQ

Frequently asked questions

What is a Go cheat sheet?

A Go cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Go. It helps developers quickly look up syntax without searching through documentation.

How do I learn Go quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Go concepts?

Key Go concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Go code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Go code using AI.

Code Conversion Tools

Convert Go to Other Languages

Easily translate your Go code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Go Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week