Go Cheatsheet
10xdev.blog/cheatsheets
# 1. Basics
package main

import "fmt"

func main() {
    // Variables
    // `var` declares a variable, can include type
    var message string = "Hello, Go!"
    // `:=` is shorthand for declaring and initializing
    shorthandMessage := "This is shorter."

    fmt.Println(message, shorthandMessage)

    // Basic types
    var anInt int = 42
    var aFloat float64 = 3.14
    var isGoCool bool = true
    var aRune rune = 'G' // Alias for int32, represents a Unicode code point

    fmt.Printf("Types: %T, %T, %T, %T\n", anInt, aFloat, isGoCool, aRune)
}
# 2. Data Structures
package main

import "fmt"

func main() {
    // Arrays (fixed size)
    var arr [3]int
    arr[0] = 1
    fmt.Println("Array:", arr)

    // Slices (dynamic size, more common)
    s := []int{1, 2, 3}
    s = append(s, 4)
    fmt.Println("Slice:", s)

    // Maps (key-value pairs)
    m := make(map[string]int)
    m["one"] = 1
    m["two"] = 2
    fmt.Println("Map:", m)
    delete(m, "one")

    // Structs (custom data types)
    type User struct {
        ID   int
        Name string
    }
    u := User{ID: 1, Name: "Alice"}
    fmt.Printf("Struct: %+v\n", u)
}
# 3. Control Flow
package main

import "fmt"

func main() {
    // `for` is Go's only looping construct
    // Basic for loop
    for i := 0; i < 3; i++ {
        fmt.Println(i)
    }

    // `for` as a while loop
    j := 0
    for j < 3 {
        fmt.Println(j)
        j++
    }

    // `if/else`
    num := 9
    if num%2 == 0 {
        fmt.Println("even")
    } else {
        fmt.Println("odd")
    }

    // `switch`
    switch num {
    case 0:
        fmt.Println("Zero")
    case 9:
        fmt.Println("Nine")
    default:
        fmt.Println("Other")
    }
}
# 4. Functions
package main

import "fmt"

// Function with parameters and a return type
func add(a int, b int) int {
    return a + b
}

// Functions can return multiple values
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    sum := add(5, 3)
    fmt.Println("Sum:", sum)

    res, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", res)
    }
}
# 5. Pointers
package main

import "fmt"

// Pointers hold the memory address of a value.
// Use `&` to get the address of a variable.
// Use `*` to dereference a pointer (get the value).

func main() {
    i := 42
    p := &i // p points to i

    fmt.Println("Value of i:", *p) // read i through the pointer
    *p = 21 // set i through the pointer
    fmt.Println("New value of i:", i)
}
# 6. Error Handling
package main

import (
    "fmt"
    "strconv"
)

// Go's idiomatic error handling uses an explicit `error` type
// as the last return value from a function.

func main() {
    s := "123a"
    n, err := strconv.Atoi(s)

    if err != nil {
        // A non-nil error means something went wrong.
        fmt.Println("Error converting string to int:", err)
        return
    }

    fmt.Println("Successfully converted:", n)
}
# 7. Concurrency
package main

import (
    "fmt"
    "time"
)

// Goroutines are lightweight threads managed by the Go runtime.
func say(s string) {
    for i := 0; i < 3; i++ {
        fmt.Println(s)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    // Start a new goroutine with the `go` keyword.
    go say("world")
    say("hello")

    // Channels are used to communicate between goroutines.
    ch := make(chan string)

    go func() {
        ch <- "ping" // Send a value into the channel
    }()

    msg := <-ch // Receive a value from the channel
    fmt.Println(msg)
}
# 8. Go Modules
# 1. Initialize a new module (creates go.mod)
go mod init example.com/my-project

# 2. Add dependencies (they are automatically added on import)
# Just add `import "rsc.io/quote"` to a .go file

# 3. Tidy up dependencies (removes unused, adds missing)
go mod tidy

# 4. Build the project
go build

# 5. Run the project
go run .

# 6. Run tests
go test ./...
master* 0 0