Go Cheatsheet

Go Basics and Syntax

Use this Go reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Program Structure

Every Go file belongs to a package. Execution starts at main.main.

package main

import (
    "fmt"
    "math"
)

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

Variables and Constants

var declarations

var x int           // zero value: 0
var s string        // zero value: ""
var b bool          // zero value: false
var f float64       // zero value: 0.0

var x, y int = 1, 2        // multiple with initializer
var (                        // grouped
    name string = "Alice"
    age  int    = 30
)

Short variable declaration (:=)

Only inside functions. Infers type from value.

x := 42
s := "hello"
a, b := 1, 2
a, b = b, a    // swap (no :=; both already declared)

Constants

const Pi = 3.14159
const (
    StatusOK    = 200
    StatusNotFound = 404
)

iota — auto-incrementing integer constants

type Direction int
const (
    North Direction = iota // 0
    East                   // 1
    South                  // 2
    West                   // 3
)

const (
    _  = iota       // skip 0
    KB = 1 << (10 * iota) // 1024
    MB                    // 1048576
    GB
)

Primitive Types

TypeWidthRange / Notes
bool1 bytetrue, false
intplatform32 or 64 bit
int88 bits-128..127
int1616 bits-32768..32767
int3232 bitsalso rune (Unicode code point)
int6464 bits
uint, uint8uint64unsigneduint8 also byte
uintptrplatformstores a raw pointer value
float3232 bits~7 sig digits
float6464 bits~15 sig digits (default)
complex6464 bitscomplex(r, i)
complex128128 bits
stringimmutable UTF-8 bytes
runeint32Unicode code point
byteuint8alias
var i int     = 42
var f float64 = float64(i)  // explicit conversion required
var u uint    = uint(f)

Type Conversions

Go has no implicit numeric conversion. Always explicit.

i := 42
f := float64(i)
s := string(rune(65))   // "A"  — int to rune/string
n, _ := strconv.Atoi("42")        // string → int
str   := strconv.Itoa(42)         // int → string
f2, _ := strconv.ParseFloat("3.14", 64)
b, _  := strconv.ParseBool("true")

Zero Values

Every uninitialized variable gets its type's zero value.

TypeZero value
numeric0
boolfalse
string""
pointer, slice, map, chan, func, interfacenil

Operators

Arithmetic

OperatorDescription
+add / string concat
-subtract
*multiply
/divide (integer div truncates)
%modulo

Comparison

== != < <= > >= — return bool

Logical

&& || !

Bitwise

OperatorDescription
&AND
|OR
^XOR (binary) or bitwise NOT (unary)
&^AND NOT (bit clear)
<<left shift
>>right shift

Assignment shortcuts

+= -= *= /= %= &= |= ^= <<= >>=

Go has no ++/-- expressions — only statements (i++, i--).

Strings

Strings are immutable sequences of bytes (UTF-8).

s := "hello"
r := `raw\nliteral`       // backtick: no escape processing

len(s)                    // byte count, not rune count
s[0]                      // byte (uint8), not rune
s[1:3]                    // slice: "el"
s + " world"              // concatenation

// iterate over runes
for i, ch := range s {
    fmt.Printf("%d: %c\n", i, ch) // ch is rune
}

Common strings package functions

FunctionDescription
strings.Contains(s, sub)reports whether sub is in s
strings.HasPrefix(s, p)starts with p
strings.HasSuffix(s, p)ends with p
strings.Count(s, sub)non-overlapping count
strings.Index(s, sub)first index, -1 if absent
strings.LastIndex(s, sub)last index
strings.Replace(s, old, new, n)replace n occurrences (-1 = all)
strings.ReplaceAll(s, old, new)replace all
strings.ToUpper(s)uppercase
strings.ToLower(s)lowercase
strings.TrimSpace(s)strip leading/trailing whitespace
strings.Trim(s, cutset)strip chars in cutset
strings.TrimLeft/Rightstrip from one end
strings.TrimPrefix/Suffixstrip exact prefix/suffix
strings.Split(s, sep)split → []string
strings.SplitN(s, sep, n)split at most n parts
strings.Join(parts, sep)join []string
strings.Fields(s)split on any whitespace
strings.Repeat(s, n)repeat n times
strings.EqualFold(a, b)case-insensitive equality
strings.ContainsRune(s, r)contains rune
strings.Map(f, s)apply f to each rune
strings.NewReader(s)returns *strings.Reader
strings.Builderefficient incremental build
import "strings"

strings.Split("a,b,c", ",")           // ["a" "b" "c"]
strings.Join([]string{"a","b"}, "-")  // "a-b"
strings.TrimSpace("  hi  ")           // "hi"
strings.Replace("aaa", "a", "b", 2)  // "bba"

var b strings.Builder
b.WriteString("hello")
b.WriteByte(' ')
b.WriteRune('🌍')
result := b.String()

fmt — Formatted I/O

Print functions

fmt.Print(...)        // no newline
fmt.Println(...)      // adds newline
fmt.Printf(fmt, ...) // formatted
s := fmt.Sprintf(fmt, ...) // returns string
fmt.Fprintf(w, fmt, ...) // write to io.Writer
fmt.Fprintln(w, ...)

Common verbs

VerbMeaning
%vdefault format
%+vstruct with field names
%#vGo syntax representation
%Ttype
%dinteger decimal
%bbinary
%ooctal
%x / %Xhex lower/upper
%ffloat decimal
%e / %Escientific notation
%gshortest float representation
%sstring
%qdouble-quoted string
%crune (character)
%ppointer
%tbool
%wwrap error (in fmt.Errorf)
%%literal %

Width and precision: %8d (right-align, width 8), %-8d (left-align), %08d (zero-pad), %.2f (2 decimal places), %8.2f (both).

fmt.Printf("%q\n", "hello")     // "hello"
fmt.Printf("%08.2f\n", 3.14)   // 00003.14
fmt.Printf("%T\n", 42)          // int

Scan functions

fmt.Scan(&x)          // whitespace-separated
fmt.Scanln(&x, &y)   // up to newline
fmt.Scanf("%d", &x)  // formatted
fmt.Sscanf(s, "%d %s", &n, &name) // from string

Arrays

Fixed-length; value type (copied on assignment).

var a [5]int            // [0 0 0 0 0]
b := [3]string{"a", "b", "c"}
c := [...]int{1, 2, 3} // length inferred

a[0] = 10
len(a)                  // 5

// 2D
matrix := [2][3]int{{1,2,3},{4,5,6}}

Arrays are rarely used directly — prefer slices.

Blank Identifier

_ discards a value.

for _, v := range slice { ... }
x, _ := someFunc()
import _ "pkg"          // side-effects only import