ZEN Software ENGIneer

Golang Cheatsheet: Complete Syntax Guide

golang-nerd-banner.png

Golang Cheatsheet: Complete Syntax Guide

1. Package Declaration & Imports

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

2. Variables & Data Types

var name string = "Alice"   // explicit type
var age = 25                // type inferred
city := "Jakarta"           // shorthand declaration (inside functions only)
 var x, y int = 1, 2         // multiple variables, same type
a, b := 5, "hello"          // multiple variables, mixed types
 const Pi = 3.14159          // constant, cannot be changed

Basic types:

TypeDescriptionExample
int, int8, int32, int64Whole numbers10
float32, float64Decimal numbers3.14
stringText"hello"
boolTrue/falsetrue
byteAlias for uint8'A'
runeAlias for int32, represents a Unicode character'あ'

3. Control Structures

If / Else

if age >= 18 {
    fmt.Println("Adult")
} else if age >= 13 {
    fmt.Println("Teenager")
} else {
    fmt.Println("Child")
}
 // If with a short statement before the condition
if err := doSomething(); err != nil {
    fmt.Println("Error occurred")
}

For Loop

Go has only one looping keyword: for. It handles all loop styles.

// Classic three-part loop
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
 // While-style loop (condition only)
n := 0
for n < 5 {
    n++
}
 // Infinite loop
for {
    fmt.Println("runs forever")
    break // must have a break somewhere to stop
}
 // Range loop (iterate over slices, arrays, maps, strings)
nums := []int{10, 20, 30}
for index, value := range nums {
    fmt.Println(index, value)
}

Switch

switch day {
case "Mon", "Tue", "Wed", "Thu", "Fri":
    fmt.Println("Weekday")
case "Sat", "Sun":
    fmt.Println("Weekend")
default:
    fmt.Println("Invalid day")
}
 // Switch without a condition (acts like if-else chain)
switch {
case age < 13:
    fmt.Println("Child")
case age < 20:
    fmt.Println("Teenager")
default:
    fmt.Println("Adult")
}

4. Functions

func add(a int, b int) int {
    return a + b
}
 // Shorthand when parameters share a type
func multiply(a, b int) int {
    return a * b
}
 // Multiple return values
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}
 // Named return values
func rectangleArea(width, height float64) (area float64) {
    area = width * height
    return // "naked" return, uses the named variable
}
 // Variadic functions (accepts any number of arguments)
func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

5. Structs & Methods

type Person struct {
    Name string
    Age  int
}
 // Method with value receiver (works on a copy)
func (p Person) Greet() string {
    return "Hi, I'm " + p.Name
}
 // Method with pointer receiver (can modify the original)
func (p *Person) Birthday() {
    p.Age++
}
 p := Person{Name: "Alice", Age: 25}
p.Birthday()
fmt.Println(p.Age) // 26

6. Interfaces

type Greeter interface {
    Greet() string
}
 func printGreeting(g Greeter) {
    fmt.Println(g.Greet())
}

7. Slices & Arrays

// Array: fixed size
var arr [3]int = [3]int{1, 2, 3}
 // Slice: dynamic size, backed by an array
nums := []int{1, 2, 3}
nums = append(nums, 4)        // adds an element
sub := nums[1:3]              // slicing: index 1 up to (not including) 3

8. Maps

ages := map[string]int{
    "Alice": 25,
    "Bob":   30,
}
 ages["Charlie"] = 28          // add/update
value, exists := ages["Dave"] // check existence
delete(ages, "Bob")           // remove a key

9. Pointers

x := 10
p := &x        // p holds the memory address of x
*p = 20        // dereference: change the value x points to
fmt.Println(x) // 20

10. Goroutines & Channels (Concurrency)

func sayHello() {
    fmt.Println("Hello from goroutine!")
}
 func main() {
    go sayHello()   // runs concurrently, doesn't block main
     ch := make(chan string)
    go func() {
        ch <- "data sent"   // send value into channel
    }()
    msg := <-ch              // receive value from channel (blocks until data arrives)
    fmt.Println(msg)
}

11. Error Handling

result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println("Result:", result)
 // Wrapping errors
if err != nil {
    return fmt.Errorf("operation failed: %w", err)
}

12. Defer, Panic, Recover

func readFile() {
    fmt.Println("opening file")
    defer fmt.Println("closing file") // runs when function returns
     panic("something went wrong")
}
 func safeCall() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered from:", r)
        }
    }()
    panic("boom")
}

13. Packages & Modules

go mod init myproject       # create a new module (go.mod file)
go get github.com/pkg/x     # add an external dependency
go run main.go              # compile and run immediately
go build                    # compile into a binary
go test                     # run tests in the current package
go fmt                      # auto-format code

That's the full syntax rundown — every core building block from variables to concurrency. Want a follow-up cheatsheet on generics (Go 1.18+), the context package, or testing conventions?