Go Cheatsheet

1. Variables and Data Types

var age int = 30
var isStudent bool = true
var pi float64 = 3.14159
name := "John"  // Short variable declaration

// Arrays and Slices
numbers := [3]int{1, 2, 3}
slice := []int{1, 2, 3, 4}

// Maps
person := map[string]int{"age": 30, "year": 1990}

// Constants
const Pi = 3.14159

2. Control Flow (Conditionals and Loops)

if age > 18 {
  fmt.Println("Adult")
} else {
  fmt.Println("Minor")
}

// Switch statement
switch day := 2; day {
  case 1:
    fmt.Println("Monday")
  case 2:
    fmt.Println("Tuesday")
  default:
    fmt.Println("Other day")
}

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

// Range loop
for i, value := range slice {
  fmt.Println(i, value)
}

// Defer
defer fmt.Println("Deferred until the end")

3. Functions and Closures

func greet(name string) string {
  return "Hello, " + name
}
fmt.Println(greet("John"))

// Multiple return values
func addAndMultiply(a, b int) (int, int) {
  return a + b, a * b
}
sum, product := addAndMultiply(2, 3)
fmt.Println(sum, product)

// Anonymous function (Closure)
closure := func(x int) int {
  return x * x
}
fmt.Println(closure(5))

4. Structs, Methods, and Composition

type Person struct {
  Name string
  Age  int
}

// Method with receiver
func (p Person) Greet() string {
  return "Hello, my name is " + p.Name
}

p := Person{Name: "John", Age: 30}
fmt.Println(p.Greet())

// Composition

type Employee struct {
  Person
  EmployeeID int
}
e := Employee{Person: Person{Name: "Jane", Age: 25}, EmployeeID: 12345}
fmt.Println(e.Greet())  // Inherited method

5. Interfaces and Polymorphism

type Animal interface {
  Speak() string
}

type Dog struct {}
func (d Dog) Speak() string {
  return "Woof!"
}

type Cat struct {}
func (c Cat) Speak() string {
  return "Meow!"
}

func makeAnimalSpeak(a Animal) {
  fmt.Println(a.Speak())
}

makeAnimalSpeak(Dog{})
makeAnimalSpeak(Cat{})

6. Goroutines and Concurrency

func printNumbers() {
  for i := 1; i <= 5; i++ {
    fmt.Println(i)
  }
}

go printNumbers()  // Run in a separate Goroutine

fmt.Println("Hello from main")
time.Sleep(1 * time.Second)  // Wait for Goroutines to finish

// Synchronization with WaitGroup
var wg sync.WaitGroup
wg.Add(1)
go func() {
  printNumbers()
  wg.Done()
}()
wg.Wait()

7. Channels and Select

messages := make(chan string)

// Sending to a channel
go func() {
  messages <- "Hello, Go!"
}()

// Receiving from a channel
msg := <-messages
fmt.Println(msg)

// Buffered channel
buffered := make(chan int, 2)
buffered <- 1
buffered <- 2
fmt.Println(<-buffered)
fmt.Println(<-buffered)

// Using select with channels
go func() { messages <- "Hi!" }()
select {
  case msg := <-messages:
    fmt.Println(msg)
  case <-time.After(1 * time.Second):
    fmt.Println("Timeout")
}

8. Error Handling and Panics

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

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

// Panic and recover
func riskyOperation() {
  defer func() {
    if r := recover(); r != nil {
      fmt.Println("Recovered from:", r)
    }
  }()
  panic("Something went wrong!")
}
riskyOperation()

9. Go Modules and Packages

// Initialize a Go module
go mod init example.com/myapp

// Importing and creating packages
package mypackage
func MyFunction() string {
  return "Hello from my package"
}

// Use in main.go
import "example.com/mypackage"
fmt.Println(mypackage.MyFunction())

10. Testing and Benchmarking

// Writing a unit test
import "testing"

func TestAdd(t *testing.T) {
  got := add(2, 3)
  want := 5
  if got != want {
    t.Errorf("got %d, want %d", got, want)
  }
}

// Writing a benchmark
testing.Benchmark(func(b *testing.B) {
  for i := 0; i < b.N; i++ {
    add(2, 3)
  }
})

11. Memory Management and Garbage Collection

// Working with pointers
x := 10
ptr := &x  // Pointer to x

fmt.Println(*ptr)  // Dereferencing the pointer
*ptr = 20
fmt.Println(x)  // x is now 20

// Go's garbage collection automatically reclaims memory

12. Context for Cancellation and Timeouts

import "context"

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

select {
  case <-time.After(1 * time.Second):
    fmt.Println("Finished work")
  case <-ctx.Done():
    fmt.Println("Context canceled:", ctx.Err())
}

13. JSON Handling and Marshalling

import "encoding/json"

// Encoding to JSON
person := map[string]string{"name": "John", "age": "30"}
jsonData, _ := json.Marshal(person)
fmt.Println(string(jsonData))

// Decoding from JSON
var data map[string]string
json.Unmarshal(jsonData, &data)
fmt.Println(data["name"])

14. Reflection

import "reflect"

x := 10
fmt.Println("Type of x:", reflect.TypeOf(x))
fmt.Println("Value of x:", reflect.ValueOf(x))

// Reflecting on struct fields
type Person struct {
  Name string
  Age  int
}
p := Person{"John", 30}
t := reflect.TypeOf(p)
for i := 0; i < t.NumField(); i++ {
  field := t.Field(i)
  fmt.Println(field.Name, field.Type)
}

15. File Handling

file, err := os.Create("example.txt")
if err != nil {
  log.Fatal(err)
}
defer file.Close()

file.WriteString("Hello, Go!")

// Reading from a file
content, err := ioutil.ReadFile("example.txt")
if err != nil {
  log.Fatal(err)
}
fmt.Println(string(content))