Go cheat sheet
96 one-line examples for Go. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Print and Input
| Code | What it does |
|---|---|
fmt.Println("Hello") | Print a line with a newline at the end. |
fmt.Print("Hi") | Print text with no newline. |
fmt.Printf("%d\n", n) | Print a value with a format verb. |
fmt.Sprintf("%d", n) | Build a string and return it. |
fmt.Scan(&name) | Read one word into a variable. |
fmt.Scanln(&name) | Read a line into a variable. |
var n int | Declare a variable with a zero value. |
n := 5 | Declare and assign inside a function. |
const Pi = 3.14 | Declare a constant value. |
fmt.Println(len(s)) | Print the byte length of a string. |
fmt.Printf("%v\n", x) | Print any value in default format. |
fmt.Printf("%T\n", x) | Print the type of a value. |
Variables and Types
| Code | What it does |
|---|---|
var s string = "go" | Declare a string with a type. |
var b bool = true | Declare a boolean value. |
var f float64 = 1.5 | Declare a 64-bit float. |
var r rune = 'A' | Declare a rune for one character. |
var by byte = 65 | Declare a byte value. |
x := 10 | Short declaration infers the type. |
a, b := 1, 2 | Declare two variables at once. |
x = 20 | Assign a new value to a variable. |
x++ | Add one to a number. |
x += 3 | Add three to a number. |
var p *int = &x | Declare a pointer to an int. |
*p = 7 | Change the value through a pointer. |
Control Flow
| Code | What it does |
|---|---|
if x > 0 { } | Run a block when the test is true. |
if x > 0 { } else { } | Run one of two blocks. |
if x := f(); x > 0 { } | Run a statement before the test. |
for i := 0; i < 5; i++ { } | Loop five times with a counter. |
for x < 10 { } | Loop while a condition is true. |
for { } | Loop forever until a break. |
break | Exit the loop now. |
continue | Skip to the next loop step. |
for i, v := range xs { } | Loop over a slice with index and value. |
for k, v := range m { } | Loop over a map with key and value. |
switch x { case 1: } | Choose a block by value. |
switch { case x > 0: } | Choose a block by condition. |
Functions
| Code | What it does |
|---|---|
func add(a, b int) int { } | Declare a function with two int parameters. |
return a + b | Return a value from a function. |
func f() (int, int) { } | Return two values from a function. |
a, b := f() | Get two return values. |
func f() (n int) { } | Declare a named return value. |
func f(xs ...int) { } | Accept a variable number of arguments. |
f(1, 2, 3) | Call a variadic function. |
defer f.Close() | Run a call when the function returns. |
func(x int) int { } | Write an anonymous function. |
f := func() { } | Store a function in a variable. |
func f(g func(int)) { } | Take a function as a parameter. |
func (t T) M() { } | Declare a method on a type. |
Slices and Arrays
| Code | What it does |
|---|---|
var a [3]int | Declare a fixed array of three ints. |
a := [3]int{1, 2, 3} | Create an array with values. |
s := []int{1, 2, 3} | Create a slice with values. |
s := make([]int, 0) | Make an empty slice with length zero. |
s := make([]int, 3) | Make a slice with length three. |
s = append(s, 4) | Add a value to the end of a slice. |
n := len(s) | Get the number of items in a slice. |
c := cap(s) | Get the capacity of a slice. |
s[0] | Read the first item of a slice. |
s[1:3] | Get items one and two. |
copy(dst, src) | Copy items from one slice to another. |
for _, v := range s { } | Loop over slice values only. |
Maps and Structs
| Code | What it does |
|---|---|
m := map[string]int{} | Create an empty map. |
m := make(map[string]int) | Make an empty map with make. |
m["a"] = 1 | Set a value for a key. |
v := m["a"] | Read a value for a key. |
v, ok := m["a"] | Read a value and check the key. |
delete(m, "a") | Remove a key from a map. |
len(m) | Get the number of keys in a map. |
type P struct { X int } | Declare a struct type with one field. |
p := P{X: 1} | Create a struct value with a field. |
p.X = 2 | Set a struct field. |
p := &P{X: 1} | Create a pointer to a struct. |
type ID int | Declare a new named type. |
Errors and Files
| Code | What it does |
|---|---|
err := f() | Get an error from a function call. |
if err != nil { } | Check that no error occurred. |
return fmt.Errorf("bad: %w", err) | Wrap an error with more context. |
errors.Is(err, ErrX) | Check if an error matches a target. |
panic("stop") | Stop the program with a message. |
defer func() { recover() }() | Catch a panic in a function. |
f, err := os.Open(p) | Open a file and get an error. |
defer f.Close() | Close the file when the function ends. |
data, err := os.ReadFile(p) | Read a whole file into memory. |
err := os.WriteFile(p, b, 0644) | Write bytes to a file. |
sc := bufio.NewScanner(f) | Make a scanner to read lines. |
for sc.Scan() { } | Loop over each line of input. |
Packages and Tests
| Code | What it does |
|---|---|
package main | Declare the main package for a program. |
import "fmt" | Import one package. |
import ( "os" ) | Import packages in a group. |
func main() { } | Declare the program entry point. |
fmt.Println(os.Args[1]) | Read the first command line argument. |
go run main.go | Build and run a Go file. |
go build | Build the program in this folder. |
go mod init app | Start a new module named app. |
go test ./... | Run all tests in the module. |
func TestAdd(t *testing.T) { } | Declare a test function. |
if got != want { t.Fatal() } | Fail the test when values differ. |
go vet ./... | Check code for common mistakes. |