Go

The Go Programming Language Cheat Sheet

Introduction

Go is a statically typed, compiled programming language designed for simplicity, efficiency, and ease of use. It was developed at Google and is widely used for building scalable and reliable software systems.

Basic Syntax

  • Variables: var variableName type
  • Constants: const constantName type = value
  • Functions: func functionName(parameters) returnType { ... }
  • Control Flow: if condition { ... } else if condition { ... } else { ... }
  • Loops: for initialization; condition; increment { ... }
  • Arrays: var arrayName [size]type
  • Slices: var sliceName []type
  • Maps: var mapName map[keyType]valueType

Data Types

  • Numeric Types: int, float32, float64
  • String Type: string
  • Boolean Type: bool
  • Composite Types: array, slice, map, struct

Pointers

Go supports pointers, which allow you to directly manipulate memory addresses. Use the & operator to get the address of a variable, and the * operator to access the value at a memory address.

Packages

Go organizes code into packages. Use the import keyword to import packages, and the package keyword to define a package. Packages can be imported using the dot notation, e.g., import . "fmt".

Error Handling

Go encourages explicit error handling. Functions that can return an error typically have a return type of (result, error). Use the if err != nil pattern to check for errors.

Concurrency

Go has built-in support for concurrency through goroutines and channels. Goroutines are lightweight threads, and channels are used for communication between goroutines.

Resources