Go Language Cheat Sheet

Here’s a cheat sheet for the Go programming language (also known as Golang). Go is a statically typed, compiled language designed for simplicity, efficiency, and ease of use. It’s commonly used for developing web applications, system tools, and distributed systems.

Hello World

package main

import "fmt"

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

Variables

var a int           // Declaration without initialization
var b = 42           // Declaration with initialization
c := 3.14           // Short declaration (inside functions)

const pi = 3.14159  // Constant declaration

Data Types

// Numeric Types
var intVar int
var floatVar float64

// String
var strVar string

// Boolean
var boolVar bool

Functions

func add(x, y int) int {
    return x + y
}

result := add(5, 3)

Control Flow

// If statement
if x > 0 {
    // do something
} else {
    // do something else
}

// Switch statement
switch day {
case "Monday":
    // do something
case "Tuesday":
    // do something else
default:
    // default case
}

Loops

// For loop
for i := 0; i < 5; i++ {
    // do something
}

// While loop (no while keyword)
sum := 0
for sum < 10 {
    sum += 2
}

Arrays and Slices

// Arrays
var arr [3]int
arr[0] = 1
arr[1] = 2

// Slices
slice := []int{1, 2, 3, 4, 5}

Maps

// Map
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
value := m["two"]

Structs

// Struct
type Person struct {
    Name    string
    Age     int
}

// Creating an instance
p := Person{Name: "John", Age: 30}

Pointers

// Pointers
var x int = 42
var p *int = &x  // pointer to x

Interfaces

// Interface
type Shape interface {
    Area() float64
}

// Implementing the interface
type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

Packages

// Importing packages
import (
    "fmt"
    "math"
)

// Exported names must start with an uppercase letter
fmt.Println(math.Pi)

Error Handling

// Error handling
result, err := someFunction()
if err != nil {
    fmt.Println("Error:", err)
}

Concurrency (Goroutines)

// Goroutine
go func() {
    // concurrent code
}()

This cheat sheet covers some of the basics of the Go programming language. For more detailed information, refer to the official Go documentation.