Go Cheat Sheet
Complete reference guide for Go with interactive examples and live playground links
Click on any section to jump directly to it
Basic Syntax
Hello World
The classic first program: outputting text to the console.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Variables and Data Types
Variable declaration and basic data types in Go
// Variable declaration
var name string = "Go"
var age int = 30
var height float64 = 5.9
var isActive bool = true
// Short variable declaration
name := "Go"
age := 30
height := 5.9
isActive := true
// Multiple variables
var (
firstName string
lastName string
age int
)
String Operations
Common string operations and formatting techniques
package main
import (
"fmt"
"strings"
)
func main() {
text := "Hello World"
// String methods
fmt.Println(strings.ToUpper(text)) // HELLO WORLD
fmt.Println(strings.ToLower(text)) // hello world
fmt.Println(strings.Replace(text, "World", "Go", 1)) // Hello Go
fmt.Println(strings.Split(text, " ")) // [Hello World]
fmt.Println(len(text)) // 11
// String formatting
name := "Alice"
age := 25
fmt.Printf("My name is %s and I'm %d years old\n", name, age)
}
Arrays and Slices
Working with arrays and slices, basic operations
// Arrays (fixed size)
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
numbers := [...]int{1, 2, 3, 4, 5} // Compiler counts elements
// Slices (dynamic size)
fruits := []string{"apple", "banana", "cherry"}
fruits = append(fruits, "orange")
fruits = append(fruits, "grape", "mango")
// Slice operations
fmt.Println(fruits[0]) // apple
fmt.Println(fruits[1:3]) // [banana cherry]
fmt.Println(len(fruits)) // 6
fmt.Println(cap(fruits)) // capacity
Print & Input
Output and input operations
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
// Print statements
fmt.Println("Hello World")
fmt.Printf("My name is %s\n", name)
fmt.Print("Age: ", age)
// User input
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
var age int
fmt.Print("Enter your age: ")
fmt.Scan(&age)
}
Comments
Different ways to add comments
// Single line comment
/*
Multi-line comment
This is a block comment
*/
// Package documentation
// Package main provides ...
package main
Control Flow
Conditional Statements
Conditional logic and decision making
// If-else
age := 18
if age >= 18 {
fmt.Println("Adult")
} else if age >= 13 {
fmt.Println("Teenager")
} else {
fmt.Println("Child")
}
// If with initialization
if age := 18; age >= 18 {
fmt.Println("Adult")
}
// Switch statement
switch age {
case 18:
fmt.Println("Just became adult")
case 13:
fmt.Println("Just became teenager")
default:
fmt.Println("Other age")
}
Loops
Different types of loops and iterations
// For loop (Go's only loop)
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-like loop
count := 0
for count < 5 {
fmt.Println(count)
count++
}
// Infinite loop
for {
// do something
if condition {
break
}
}
// Range loop
fruits := []string{"apple", "banana", "cherry"}
for i, fruit := range fruits {
fmt.Printf("%d: %s\n", i, fruit)
}
Error Handling
Error handling patterns and custom errors
// Basic error handling
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Custom error
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
// Error checking
if err := validate(); err != nil {
switch e := err.(type) {
case *ValidationError:
fmt.Println("Validation error:", e.Message)
default:
fmt.Println("Unknown error:", err)
}
}
Functions
Function Definition
Function definition, parameters, and return values
// Basic function
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Named return values
func calculate(x, y int) (sum, product int) {
sum = x + y
product = x * y
return
}
// Variadic function
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
Methods and Interfaces
Methods, interfaces, and object-oriented patterns
// Method definition
type Person struct {
Name string
Age int
}
func (p Person) Introduce() string {
return fmt.Sprintf("Hi, I'm %s and I'm %d years old", p.Name, p.Age)
}
// Interface definition
type Speaker interface {
Speak() string
}
// Interface implementation
type Dog struct {
Name string
}
func (d Dog) Speak() string {
return fmt.Sprintf("%s says Woof!", d.Name)
}
Concurrency
Goroutines
Working with goroutines and basic concurrency
// Basic goroutine
go func() {
fmt.Println("Running in goroutine")
}()
// Goroutine with channel
ch := make(chan string)
go func() {
ch <- "Hello from goroutine"
}()
msg := <-ch
// Multiple goroutines
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d\n", id)
}(i)
}
wg.Wait()
Channels
Channel operations and select statement
// Channel creation
ch := make(chan int) // Unbuffered
ch := make(chan int, 5) // Buffered
// Channel operations
ch <- 42 // Send
value := <-ch // Receive
close(ch) // Close
// Select statement
select {
case msg := <-ch1:
fmt.Println("Received from ch1:", msg)
case msg := <-ch2:
fmt.Println("Received from ch2:", msg)
case <-time.After(time.Second):
fmt.Println("Timeout")
default:
fmt.Println("No message ready")
}
Data Structures
Maps
Map operations and common patterns
// Map creation
person := map[string]interface{}{
"name": "Alice",
"age": 30,
"city": "New York",
}
// Map operations
person["job"] = "Engineer" // Add/update
delete(person, "age") // Delete
age, exists := person["age"] // Check existence
// Map iteration
for key, value := range person {
fmt.Printf("%s: %v\n", key, value)
}
Structs
Struct definition and usage
// Struct definition
type Person struct {
Name string
Age int
Address struct {
Street string
City string
Country string
}
}
// Struct initialization
p := Person{
Name: "Alice",
Age: 30,
Address: struct {
Street string
City string
Country string
}{
Street: "123 Main St",
City: "New York",
Country: "USA",
},
}
Go - Interactive Developer Reference
Hover over code blocks to copy or run in live playground