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
| Type | Width | Range / Notes |
|---|---|---|
bool | 1 byte | true, false |
int | platform | 32 or 64 bit |
int8 | 8 bits | -128..127 |
int16 | 16 bits | -32768..32767 |
int32 | 32 bits | also rune (Unicode code point) |
int64 | 64 bits | |
uint, uint8–uint64 | unsigned | uint8 also byte |
uintptr | platform | stores a raw pointer value |
float32 | 32 bits | ~7 sig digits |
float64 | 64 bits | ~15 sig digits (default) |
complex64 | 64 bits | complex(r, i) |
complex128 | 128 bits | |
string | — | immutable UTF-8 bytes |
rune | int32 | Unicode code point |
byte | uint8 | alias |
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.
| Type | Zero value |
|---|---|
| numeric | 0 |
| bool | false |
| string | "" |
| pointer, slice, map, chan, func, interface | nil |
Operators
Arithmetic
| Operator | Description |
|---|---|
+ | add / string concat |
- | subtract |
* | multiply |
/ | divide (integer div truncates) |
% | modulo |
Comparison
== != < <= > >= — return bool
Logical
&& || !
Bitwise
| Operator | Description |
|---|---|
& | 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
| Function | Description |
|---|---|
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/Right | strip from one end |
strings.TrimPrefix/Suffix | strip 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.Builder | efficient 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
| Verb | Meaning |
|---|---|
%v | default format |
%+v | struct with field names |
%#v | Go syntax representation |
%T | type |
%d | integer decimal |
%b | binary |
%o | octal |
%x / %X | hex lower/upper |
%f | float decimal |
%e / %E | scientific notation |
%g | shortest float representation |
%s | string |
%q | double-quoted string |
%c | rune (character) |
%p | pointer |
%t | bool |
%w | wrap 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