Go Syntax Cheat Sheet: Quick Reference for Developers
This cheat sheet is a concise reference for the most frequently used Go language constructs. It is designed for developers who already understand the basics and need a quick reminder, and for newcomers who want a high‑level overview of Go’s syntax. For in‑depth explanations and tutorials, follow the links to the dedicated Foundations articles.
Program Structure
Every Go program consists of packages, imports, and a main function when producing an executable.
package main
import "fmt"
func main() {
fmt.Println("Hello, Go")
}
- The
mainpackage defines an executable. importbrings packages into scope.func main()is the entry point.
Variables and Constants
var name string = "Go" // explicit declaration
age := 10 // short declaration (inside functions)
const Pi = 3.14159 // constant
var x, y int // multiple variables with zero values
- Variables can be declared with
varor:=. :=can only be used inside functions.- Constants are declared with
const. - Uninitialised variables have zero values (
0,"",nil, etc.).
Basic Types
| Type | Description |
|---|---|
bool | true or false |
string | immutable sequence of bytes |
int | platform‑dependent signed integer |
int8–int64 | signed integers of specific size |
uint | platform‑dependent unsigned integer |
uint8–uint64 | unsigned integers of specific size |
float32, float64 | floating‑point numbers |
byte | alias for uint8 |
rune | alias for int32, represents a Unicode code point |
complex64, complex128 | complex numbers |
Operators
| Category | Operators |
|---|---|
| Arithmetic | +, -, *, /, % |
| Comparison | ==, !=, <, <=, >, >= |
| Logical | &&, ||, ! |
| Bitwise | &, |, ^, &^, <<, >> |
| Assignment | =, +=, -=, etc. |
Control Flow
If
if x > 0 {
// ...
} else if x < 0 {
// ...
} else {
// ...
}
// if with a short statement
if err := doSomething(); err != nil {
return err
}
Switch
switch day {
case "Monday":
// ...
case "Tuesday", "Wednesday":
// ...
default:
// ...
}
// switch without an expression
switch {
case hour < 12:
fmt.Println("morning")
default:
fmt.Println("afternoon")
}
For (the only loop construct)
// classic for
for i := 0; i < 10; i++ {
fmt.Println(i)
}
// while-like
for condition {
// ...
}
// infinite loop
for {
break
}
// range over slices, maps, strings
for index, value := range collection {
// ...
}
Functions
// basic function
func add(a int, b int) int {
return a + b
}
// multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // naked return
}
// variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// anonymous function (closure)
adder := func(a, b int) int {
return a + b
}
- Arguments of the same type can share the type declaration (
a, b int). - Named return values are useful for documentation but should not obscure code.
Structs and Methods
type Person struct {
Name string
Age int
}
// struct literal
p := Person{Name: "Alice", Age: 30}
// method with value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}
// method with pointer receiver
func (p *Person) Birthday() {
p.Age++
}
- Use a pointer receiver when the method needs to modify the receiver or to avoid copying large structs.
- Keep receiver names short and consistent (e.g.,
pforPerson).
Interfaces
type Speaker interface {
Speak() string
}
// implicit implementation: any type with Speak() string satisfies Speaker
type Dog struct{}
func (d Dog) Speak() string {
return "Woof"
}
var s Speaker = Dog{}
- Interfaces are satisfied implicitly; no
implementskeyword. - Keep interfaces small (1–3 methods). Use the empty interface
any(orinterface{}) only when truly necessary.
Error Handling
// creating errors
err := errors.New("something went wrong")
err := fmt.Errorf("user %s not found", name)
// wrapping errors (Go 1.13+)
err := fmt.Errorf("failed to process: %w", originalErr)
// checking errors
if errors.Is(err, ErrNotFound) {
// handle specific error
}
var customErr *MyError
if errors.As(err, &customErr) {
// access fields of customErr
}
- Always check errors; do not discard them with
_. - Wrap errors with
%wto preserve the original error for later inspection.
Collections
Arrays (fixed size)
var arr [3]int
arr[0] = 1
b := [2]string{"hello", "world"}
Slices (dynamic)
slice := []int{1, 2, 3}
slice = append(slice, 4)
sub := slice[1:3] // [2, 3]
// make a slice with length and capacity
s := make([]int, 5, 10)
- Slices are references to underlying arrays. They are passed by value, but the value includes a pointer to the array, so modifications can be seen by the caller.
lenreturns the number of elements;capreturns the capacity.
Maps
m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
delete(m, "a")
value, ok := m["z"] // ok is false if key not present
if !ok {
fmt.Println("not found")
}
- Maps are unordered. Iteration order is not guaranteed.
Strings
s := "hello"
len(s) // number of bytes
s[0] // byte at index 0 ('h')
for i, r := range s {
// r is a rune (Unicode code point)
}
Pointers
x := 42
p := &x // p is a pointer to x
fmt.Println(*p) // dereference: 42
*p = 21 // modify x through the pointer
- Go has no pointer arithmetic.
- Use pointers to share data and to allow functions to modify values.
Packages and Modules
// package declaration at the top of each file
package mypackage
// exported identifiers start with uppercase
func PublicFunc() {}
var PublicVar int
// unexported (private) identifiers start with lowercase
func privateFunc() {}
- A module is defined by a
go.modfile. - The module path (
example.com/myapp) is the import prefix for all its packages. go.sumrecords cryptographic hashes of dependencies for integrity.
Common Built‑in Functions
| Function | Purpose |
|---|---|
len | length of string, slice, array, map, or channel |
cap | capacity of slice, array, or channel |
make | allocate and initialise slice, map, or channel |
new | allocate zeroed memory and return a pointer |
append | add elements to a slice |
copy | copy elements from one slice to another |
delete | remove an entry from a map |
close | close a channel |
panic | abort normal execution with an error |
recover | regain control after a panic (used in deferred functions) |
Frequently Used Standard Library Packages
| Package | Purpose |
|---|---|
fmt | formatted I/O (print, scan, sprintf) |
strings | string manipulation (split, join, replace) |
bytes | byte slice operations similar to strings |
errors | error creation and inspection |
io | I/O primitives (Reader, Writer) |
os | operating system functionality |
time | date, time, and duration |
context | request‑scoped values, deadlines, cancellation |
sync | mutex, waitgroup, once |
encoding/json | JSON marshalling and unmarshalling |
net/http | HTTP client and server |
Common Go Commands
| Command | Purpose |
|---|---|
go run . | compile and run the package in the current dir |
go build | compile the package and produce a binary |
go test ./... | run all tests in the module |
go fmt ./... | format all source files |
go vet ./... | run static analysis |
go mod tidy | add missing and remove unused dependencies |
go mod download | download module dependencies |
go version | print the installed Go version |
go env | print Go environment variables |
Best Practices
- Write simple, explicit code; avoid cleverness.
- Always check and handle errors.
- Prefer composition (embedding) over inheritance.
- Define interfaces where they are used, not where they are implemented.
- Keep interfaces small (1–3 methods).
- Run
gofmt(orgo fmt) before committing. - Use Go Modules for dependency management in every project.
- Follow naming conventions:
MixedCapsfor exported names,mixedCapsfor unexported.
Related Articles
Deepen your understanding with the full Foundations articles:
- Variables, Constants, and Basic Types – detailed coverage of Go’s type system and variable declarations.
- Functions and Packages Explained – function design, multiple returns, and package organisation.
- Structs, Methods, and Interfaces – modelling data and behaviour in idiomatic Go.
- Error Handling in Go – explicit error management, wrapping, and inspection.
- Generics in Go – using type parameters for reusable code.
- Concurrency & Runtime – when you are ready, explore goroutines, channels, and the scheduler.