TechSchool
Home / Cheat sheets / Go

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

CodeWhat 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 intDeclare a variable with a zero value.
n := 5Declare and assign inside a function.
const Pi = 3.14Declare 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

CodeWhat it does
var s string = "go"Declare a string with a type.
var b bool = trueDeclare a boolean value.
var f float64 = 1.5Declare a 64-bit float.
var r rune = 'A'Declare a rune for one character.
var by byte = 65Declare a byte value.
x := 10Short declaration infers the type.
a, b := 1, 2Declare two variables at once.
x = 20Assign a new value to a variable.
x++Add one to a number.
x += 3Add three to a number.
var p *int = &xDeclare a pointer to an int.
*p = 7Change the value through a pointer.

Control Flow

CodeWhat 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.
breakExit the loop now.
continueSkip 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

CodeWhat it does
func add(a, b int) int { }Declare a function with two int parameters.
return a + bReturn 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

CodeWhat it does
var a [3]intDeclare 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

CodeWhat it does
m := map[string]int{}Create an empty map.
m := make(map[string]int)Make an empty map with make.
m["a"] = 1Set 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 = 2Set a struct field.
p := &P{X: 1}Create a pointer to a struct.
type ID intDeclare a new named type.

Errors and Files

CodeWhat 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

CodeWhat it does
package mainDeclare 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.goBuild and run a Go file.
go buildBuild the program in this folder.
go mod init appStart 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.
More on TechSchool
See the Go interview questions Python JavaScript TypeScript HTML CSS React Vue 3 Node.js Java PHP C C++ C# SQL MongoDB Redis Linux Git Docker Data Structures