Golang
Updated: September 8, 2025Categories: Languages
Printed from:
Go (Golang) Cheatsheet
Language Overview
Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It focuses on simplicity, efficiency, and robust concurrent programming.
Key Characteristics:
- Compiled language with fast execution
- Statically typed with garbage collection
- Built-in concurrency support via goroutines and channels
- Strong standard library
- Explicit error handling
- Efficient memory management
- Cross-platform compilation
Basic Syntax
Hello World
Go
12345678package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Program Structure
Go
12345678package main // Package declaration
import "fmt" // Import statements
// Main function - entry point of the program
func main() {
// Program logic
}
Data Types
Primitive Types
Go
12345678910111213141516171819202122232425// Integers
var integer int // Platform-dependent integer
var int8 int8 // 8-bit signed integer
var int16 int16 // 16-bit signed integer
var int32 int32 // 32-bit signed integer
var int64 int64 // 64-bit signed integer
// Unsigned Integers
var uint uint // Unsigned platform-dependent integer
var byte uint8 // Alias for uint8
var uint16 uint16 // 16-bit unsigned integer
// Floating Point
var float32 float32 // 32-bit floating point
var float64 float64 // 64-bit floating point
// Boolean
var boolean bool // true or false
// String
var text string // Immutable string type
// Character (rune)
var char rune // Unicode code point
Collection Types
Go
1234567891011121314151617181920// Arrays (Fixed Size)
var arr [5]int = [5]int{1, 2, 3, 4, 5}
// Slices (Dynamic Arrays)
slice := []int{1, 2, 3, 4, 5}
slice = append(slice, 6)
// Maps (Hash Tables/Dictionaries)
m := map[string]int{
"apple": 1,
"banana": 2,
}
m["orange"] = 3
// Struct
type Person struct {
Name string
Age int
}
Variables and Constants
Go
1234567891011121314// Variable Declaration
var name string = "John"
age := 30 // Short declaration (type inferred)
// Multiple Variable Declaration
var x, y int = 10, 20
// Constants
const Pi = 3.14159
const (
StatusOK = 200
NotFound = 404
)
Operators
Arithmetic Operators
Go
12345678a := 10
b := 3
sum := a + b // Addition
diff := a - b // Subtraction
prod := a * b // Multiplication
div := a / b // Division
mod := a % b // Modulus
Comparison Operators
Go
1234567a == b // Equal
a != b // Not Equal
a < b // Less Than
a > b // Greater Than
a <= b // Less Than or Equal
a >= b // Greater Than or Equal
Logical Operators
Go
1234true && false // Logical AND
true || false // Logical OR
!true // Logical NOT
Control Structures
If/Else Statements
Go
12345678910111213if x > 0 {
fmt.Println("Positive")
} else if x < 0 {
fmt.Println("Negative")
} else {
fmt.Println("Zero")
}
// Compact if statement with initialization
if y := someFunction(); y > 10 {
// Use y here
}
Loops
Go
12345678910111213141516171819202122// Traditional for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-like loop
for x < 10 {
x++
}
// Infinite loop
for {
// Do something
break // Exit condition
}
// Range-based iteration
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
Functions
Go
1234567891011121314151617181920212223242526// Basic Function
func add(a, b int) int {
return a + b
}
// Multiple Return Values
func divideNumbers(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Variadic Functions
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Function as a Variable
var operation func(int, int) int
operation = add
Pointers
Go
123456var x int = 10
var ptr *int = &x // Pointer to x
*ptr = 20 // Dereferencing and modifying value
fmt.Println(x) // Prints 20
Structs and Methods
Go
1234567891011121314type Rectangle struct {
width, height float64
}
// Method on struct
func (r Rectangle) area() float64 {
return r.width * r.height
}
// Struct with Constructor-like Function
func newRectangle(w, h float64) Rectangle {
return Rectangle{width: w, height: h}
}
Interfaces
Go
123456789type Shape interface {
area() float64
}
// Implementing Interface
func (r Rectangle) area() float64 {
return r.width * r.height
}
Error Handling
Go
123456789101112func divideNumbers(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
result, err := divideNumbers(10, 0)
if err != nil {
fmt.Println("Error:", err)
}
Concurrency
Goroutines
Go
123456func sayHello() {
fmt.Println("Hello")
}
go sayHello() // Runs concurrently
Channels
Go
123456ch := make(chan int) // Unbuffered channel
go func() {
ch <- 42 // Send value to channel
}()
value := <-ch // Receive value from channel
Synchronization
Go
12345678var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// Concurrent work
}()
wg.Wait() // Wait for goroutine to complete
File I/O
Go
123456789101112// Reading File
data, err := os.ReadFile("example.txt")
if err != nil {
log.Fatal(err)
}
// Writing File
err = os.WriteFile("output.txt", []byte("Hello"), 0644)
if err != nil {
log.Fatal(err)
}
Package Management
Bash
123456789# Initialize a new module
go mod init myproject
# Add a dependency
go get github.com/some/package
# Update dependencies
go mod tidy
Testing
Go
12345678// example_test.go
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
Best Practices
- Use
gofmtfor consistent code formatting - Prefer composition over inheritance
- Keep functions small and focused
- Handle all errors explicitly
- Use interfaces for flexibility
- Leverage goroutines for concurrent tasks
- Use the race detector (
go run -race)
Performance Tips
- Use
sync.Poolfor object reuse - Minimize allocations
- Use benchmarking (
testing.B) - Profile your code (
pprof) - Choose appropriate data structures
Resources for Further Learning
- Official Go Documentation: https://golang.org/doc/
- Go Tour: https://tour.golang.org/
- Effective Go: https://golang.org/doc/effective_go.html
- Go by Example: https://gobyexample.com/
- "The Go Programming Language" book by Alan A. A. Donovan and Brian W. Kernighan
Continue Learning
Discover more cheatsheets to boost your productivity