Go-Cheatsheet

👋 Hello World

package main
import "fmt"

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

💡 Tip: Every Go program starts with package main and a main() function.

📦 Variables & Constants

package main
import "fmt"

func main() {
    var name string = "Maxon"
    age := 25 // short declaration
    const pi = 3.14159

    fmt.Println(name, age, pi)
}

💡 Tip: Use := for short variable declarations. Constants use const.

🔢 Data Types

var a int = 42
var b float64 = 3.14
var c string = "Gopher"
var d bool = true

💡 Tip: Go is statically typed but infers types automatically when possible.

🔀 Control Flow

for i := 1; i <= 5; i++ {
    if i%2 == 0 {
        fmt.Println(i, "is Even")
    } else {
        fmt.Println(i, "is Odd")
    }
}

switch day := 3; day {
case 1:
    fmt.Println("Mon")
case 2:
    fmt.Println("Tue")
default:
    fmt.Println("Other")
}

💡 Tip: Go has no while — only for loops with different forms.

🧮 Functions

func add(a int, b int) int {
    return a + b
}

func main() {
    fmt.Println(add(5, 3))
}

💡 Tip: Functions can return multiple values.

🔁 Multiple Return

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("divide by zero")
    }
    return a / b, nil
}

💡 Tip: Return multiple results (like value, error) — a Go standard.

📚 Structs

type Car struct {
    Brand string
    Speed int
}

func main() {
    c := Car{"Tesla", 120}
    fmt.Println(c.Brand, c.Speed)
}

💡 Tip: Structs are Go’s way to define custom types (like classes in OOP).

🧭 Methods

type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

💡 Tip: Methods are functions with a receiver (object-like behavior).

⚙️ Interfaces

type Shape interface {
    Area() float64
}

func PrintArea(s Shape) {
    fmt.Println(s.Area())
}

💡 Tip: Interfaces define behavior, not data — a key Go design principle.

🌐 Packages & Imports

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.Sqrt(16))
}

💡 Tip: Package management in Go is simple and dependency-light.

🔄 Arrays & Slices

arr := [3]int{1, 2, 3}
slice := []int{4, 5, 6}

slice = append(slice, 7)
fmt.Println(arr, slice)

💡 Tip: Slices are dynamic views of arrays — they grow automatically.

🗃 Maps

ages := map[string]int{
    "Maxon": 25,
    "John":  30,
}
ages["Lisa"] = 22
fmt.Println(ages)

💡 Tip: Maps are Go’s built-in hash tables.

⚡ Goroutines

func say(s string) {
    for i := 0; i < 3; i++ {
        fmt.Println(s)
    }
}

func main() {
    go say("Async")
    say("Sync")
}

💡 Tip: Use go keyword to run a function concurrently.

🔗 Channels

ch := make(chan string)

go func() {
    ch <- "Hello from channel"
}()

msg := <-ch
fmt.Println(msg)

💡 Tip: Channels let goroutines communicate safely — no locks needed.

🧩 Error Handling

result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

💡 Tip: Errors are values — check them explicitly.

📦 Modules

go mod init myapp
go get github.com/gorilla/mux

💡 Tip: Use go mod for dependency management in Go 1.11+.

🧰 JSON Handling

import "encoding/json"

type User struct {
    Name string
    Age  int
}

data, _ := json.Marshal(User{"Maxon", 25})
fmt.Println(string(data))

💡 Tip: Go’s encoding/json package makes serialization simple.

🧠 Defer, Panic, Recover

func safeDivide(a, b int) {
    defer fmt.Println("End function")
    if b == 0 {
        panic("divide by zero")
    }
    fmt.Println(a / b)
}

💡 Tip: Use defer for cleanup, panic for fatal errors, and recover to handle them.

Post a Comment