๐Ÿน Go Dictionary

Every keyword, operator, and symbol โ€” with plain-English explanations.

complex builtin
Constructs a complex number from real and imaginary float parts.
c := complex(1.0, 2.0)
errors.As stdlib
Finds the first error in the chain matching the target type and sets it.
var e *PathError; errors.As(err, &e)
goto keyword
Jumps to a labeled statement in the same function. Rarely used in modern Go.
goto cleanup
http.Error stdlib
Sends a plain text error response with the given status code.
http.Error(w, "Not found", 404)
http.Get stdlib
Makes a GET request and returns the response.
resp, err := http.Get(url)
http.NotFound stdlib
Sends a 404 Not Found response.
http.NotFound(w, r)
http.Post stdlib
Makes a POST request with a body to the given URL.
resp, err := http.Post(url, contentType, body)
http.Redirect stdlib
Sends an HTTP redirect response to the client.
http.Redirect(w, r, "/login", http.StatusFound)
http.Request stdlib
Struct representing an incoming HTTP request with URL, headers, body.
r.URL.Query().Get("name")
http.ResponseWriter stdlib
Interface passed to handlers to write the HTTP response.
func handler(w http.ResponseWriter, r *http.Request) {}
http.StatusFound stdlib
HTTP 302 Found (redirect) status code constant.
http.Redirect(w, r, "/", http.StatusFound)
http.StatusOK stdlib
HTTP 200 OK status code constant.
w.WriteHeader(http.StatusOK)
imag builtin
Returns the imaginary part of a complex number.
i := imag(c)
io.Reader stdlib
Interface for types that can read bytes. Has one method: Read(p []byte).
func ReadAll(r io.Reader) []byte {}
io.Writer stdlib
Interface for types that can write bytes. Has one method: Write(p []byte).
func WriteAll(w io.Writer, data []byte) {}
json.NewDecoder stdlib
Creates a streaming JSON decoder that reads from an io.Reader.
json.NewDecoder(r.Body).Decode(&v)
json.NewEncoder stdlib
Creates a streaming JSON encoder that writes to an io.Writer.
json.NewEncoder(w).Encode(v)
log.Fatalf stdlib
Prints a formatted log message then calls os.Exit(1).
log.Fatalf("listen: %v", err)
print builtin
Low-level print to stderr โ€” use fmt.Print for formatted output instead.
print("debug")
println builtin
Low-level println to stderr โ€” use fmt.Println for formatted output instead.
println("debug")
real builtin
Returns the real part of a complex number.
r := real(c)
strings.Replace stdlib
Returns a copy with the first n occurrences of old replaced by new. -1 replaces all.
s = strings.Replace(s, "old", "new", -1)
strings.TrimPrefix stdlib
Returns s without the leading prefix. Returns s unchanged if not present.
s = strings.TrimPrefix(s, "/api/")
sync.Once stdlib
Ensures a function runs exactly once, even across goroutines.
var once sync.Once; once.Do(setup)
uint16 type
Unsigned 16-bit integer: 0 to 65535.
var n uint16 = 65535
uint32 type
Unsigned 32-bit integer: 0 to 4294967295.
var n uint32 = 4294967295
uintptr type
Unsigned integer large enough to hold any pointer value.
var p uintptr
package keyword
Declares which package this file belongs to. Every Go file starts with a package declaration.
package main
import keyword
Brings external packages into scope so you can use their functions and types.
import "fmt"
func keyword
Defines a function. Functions are the basic building blocks of Go programs.
func add(a, b int) int { return a + b }
var keyword
Declares a variable with an explicit type or initializer.
var count int = 0
const keyword
Declares a constant โ€” a value that cannot change at runtime.
const Pi = 3.14159
type keyword
Defines a new named type or type alias.
type Celsius float64
struct keyword
Defines a composite type with named fields, similar to a record or object.
type Point struct { X, Y int }
interface keyword
Defines a set of method signatures. Any type that implements all methods satisfies the interface.
type Stringer interface { String() string }
map keyword
A built-in key-value data structure (hash table). Keys must be comparable types.
scores := map[string]int{"alice": 95}
chan keyword
A channel โ€” a typed conduit for sending and receiving values between goroutines.
ch := make(chan int)
go keyword
Launches a goroutine โ€” a lightweight concurrent function running in the background.
go doWork()
defer keyword
Schedules a function call to run just before the surrounding function returns. Runs even if there is a panic.
defer file.Close()
return keyword
Exits the current function and optionally returns values to the caller.
return x, nil
if keyword
Conditional branch. Executes the block only when the condition is true.
if err != nil { log.Fatal(err) }
else keyword
The branch executed when the if condition is false.
if x > 0 { } else { }
for keyword
The only loop construct in Go. Used as a traditional for loop, while loop, or infinite loop.
for i := 0; i < 10; i++ { }
range keyword
Iterates over elements of a slice, array, map, string, or channel.
for i, v := range nums { }
switch keyword
Multi-way branch. Cases do not fall through by default (unlike C).
switch op { case "+": return a + b }
case keyword
A branch inside a switch or select statement.
case "add": return x + y
default keyword
The fallback branch of a switch or select when no other case matches.
default: fmt.Println("unknown")
break keyword
Exits the innermost for, switch, or select statement immediately.
break
continue keyword
Skips the rest of the current loop body and starts the next iteration.
continue
fallthrough keyword
Forces execution to continue into the next case in a switch statement.
fallthrough
select keyword
Like switch but for channel operations. Blocks until one case can proceed.
select { case v := <-ch: }
make builtin
Allocates and initializes slices, maps, or channels. Returns the type itself (not a pointer).
make([]int, 10)
new builtin
Allocates zeroed memory for a type and returns a pointer to it.
p := new(int)
append builtin
Appends elements to the end of a slice, growing it if necessary.
nums = append(nums, 4, 5)
len builtin
Returns the number of elements in a slice, array, string, map, or channel buffer.
len(os.Args)
cap builtin
Returns the capacity of a slice โ€” how many elements it can hold before reallocation.
cap(s)
copy builtin
Copies elements from one slice to another. Returns the number copied.
copy(dst, src)
delete builtin
Removes a key-value pair from a map. Safe to call even if the key does not exist.
delete(m, "key")
close builtin
Closes a channel, signaling that no more values will be sent on it.
close(ch)
panic builtin
Stops normal execution and begins unwinding the stack. Used for unrecoverable errors.
panic("unexpected nil")
recover builtin
Regains control after a panic inside a deferred function.
if r := recover(); r != nil { }
int type
Signed integer โ€” platform width (32 or 64 bits). The default integer type in Go.
var n int = 42
int8 type
Signed 8-bit integer. Range: -128 to 127.
var b int8 = 100
int16 type
Signed 16-bit integer. Range: -32768 to 32767.
var s int16 = 1000
int32 type
Signed 32-bit integer. Alias: rune (for Unicode code points).
var r int32 = 65
int64 type
Signed 64-bit integer. Range: -(2^63) to 2^63-1.
var big int64 = 9999999999
uint type
Unsigned integer โ€” platform width. Cannot be negative.
var u uint = 42
uint8 type
Unsigned 8-bit integer. Range: 0 to 255. Alias: byte.
var b uint8 = 255
uint64 type
Unsigned 64-bit integer. Range: 0 to 2^64-1.
var u uint64 = 18446744073709551615
float32 type
Single-precision floating-point number (32 bits, IEEE 754).
var f float32 = 3.14
float64 type
Double-precision floating-point number (64 bits). The default float type in Go.
var f float64 = 3.14159
complex64 type
Complex number with float32 real and imaginary parts.
var c complex64 = 1 + 2i
complex128 type
Complex number with float64 real and imaginary parts.
var c complex128 = 1 + 2i
bool type
Boolean type. Only two values: true and false.
var ok bool = true
string type
An immutable sequence of bytes (UTF-8 encoded text in practice).
var s string = "hello"
byte type
Alias for uint8. Typically used to represent a single byte of data.
var b byte = 65
rune type
Alias for int32. Represents a Unicode code point (a single character).
var r rune = 8364
error type
A built-in interface with a single method: Error() string. Represents error conditions.
if err != nil { return err }
any type
Alias for interface{} (Go 1.18+). Accepts a value of any type.
var v any = 42
true constant
Boolean constant representing the truth value.
ok := true
false constant
Boolean constant representing the false value.
ok := false
nil constant
The zero value for pointers, slices, maps, channels, functions, and interfaces.
if p == nil { }
iota constant
Integer counter that resets to 0 in each const block and increments per line. Used for enumerated constants.
const ( A = iota; B; C )
:= operator
Short variable declaration. Declares and assigns in one step. Only usable inside functions.
x := 42
== operator
Equality comparison. Returns true if both sides are equal.
if x == y { }
!= operator
Not-equal comparison. Returns true if both sides differ.
if err != nil { }
&& operator
Logical AND. True only when both operands are true. Short-circuits if left is false.
if a && b { }
|| operator
Logical OR. True when at least one operand is true. Short-circuits if left is true.
if a || b { }
! operator
Logical NOT. Inverts a boolean value.
if !ok { }
<- operator
Channel send/receive operator. Sends a value into a channel or receives from it.
ch <- 42
... operator
Variadic/spread operator. In function signatures accepts any number of arguments. In calls unpacks a slice.
func f(args ...string)
* operator
Pointer dereference in expressions or pointer type in declarations. Also multiplication.
*p = 42
& operator
Address-of operator. Returns a pointer to a variable. Also bitwise AND.
p := &x
% operator
Modulo (remainder) operator. Returns the remainder of integer division.
10 % 3
++ operator
Increment statement. Increases an integer variable by 1. Not an expression in Go.
i++
-- operator
Decrement statement. Decreases an integer variable by 1.
i--
+= operator
Add-and-assign. Equivalent to x = x + y.
total += price
_ operator
Blank identifier. Discards a value โ€” used to ignore return values or suppress unused-import errors.
_, err := fmt.Println(x)
[] operator
Slice/array type prefix or index operator. []int declares a slice of ints; s[i] accesses element i.
[]string  s[0]
{} operator
Composite literal syntax. Initializes a struct, slice, map, or array with values.
Point{X: 1, Y: 2}
fmt package
The standard formatting package. Provides functions for printing, formatting, and scanning text.
import "fmt"
fmt.Println fmt
Prints arguments to stdout separated by spaces, followed by a newline.
fmt.Println("Hello, world!")
fmt.Printf fmt
Prints a formatted string to stdout using format verbs like %d, %s, %v.
fmt.Printf("x = %d\n", x)
fmt.Sprintf fmt
Formats arguments into a string and returns it without printing.
s := fmt.Sprintf("count: %d", n)
fmt.Fprintf fmt
Writes formatted output to any io.Writer (file, buffer, http.ResponseWriter, etc.).
fmt.Fprintf(os.Stderr, "error: %v\n", err)
fmt.Errorf fmt
Creates a new error value with a formatted message. Supports %w to wrap another error.
err := fmt.Errorf("file %s: %w", name, err)
fmt.Scan fmt
Reads whitespace-separated values from stdin into variables.
fmt.Scan(&x, &y)
fmt.Scanln fmt
Like fmt.Scan but stops at a newline.
fmt.Scanln(&name)
fmt.Sscanf fmt
Parses a formatted string into variables using format verbs.
fmt.Sscanf("42 3.14", "%d %f", &i, &f)
%v fmt
Format verb: prints the value in its default format. Works for any type.
fmt.Printf("%v\n", point)
%d fmt
Format verb: prints an integer in base 10 (decimal).
fmt.Printf("%d\n", 42)
%s fmt
Format verb: prints a string or byte slice without quotes.
fmt.Printf("%s\n", name)
%f fmt
Format verb: prints a floating-point number with a decimal point.
fmt.Printf("%.2f\n", 3.14159)
%T fmt
Format verb: prints the Go type of a value.
fmt.Printf("%T\n", x)
%q fmt
Format verb: prints a string in double quotes with Go escape sequences.
fmt.Printf("%q\n", s)
%x fmt
Format verb: prints an integer or string in hexadecimal (lowercase).
fmt.Printf("%x\n", 255)
%b fmt
Format verb: prints an integer in binary (base 2).
fmt.Printf("%b\n", 10)
%t fmt
Format verb: prints a boolean as true or false.
fmt.Printf("%t\n", ok)
os package
Provides OS-level functions: file I/O, environment variables, process control, and command-line arguments.
import "os"
os.Args os
A slice of strings containing the command-line arguments. os.Args[0] is the program name; os.Args[1:] are user-supplied arguments.
if len(os.Args) < 2 { fmt.Println("no args") }
os.Exit os
Terminates the program immediately with the given exit code. Deferred functions do NOT run.
os.Exit(1)
os.Open os
Opens a file for reading. Returns a *os.File and an error.
f, err := os.Open("data.txt")
os.Create os
Creates or truncates a file for writing. Returns a *os.File and an error.
f, err := os.Create("output.txt")
os.ReadFile os
Reads the entire contents of a file into a byte slice.
data, err := os.ReadFile("config.json")
os.WriteFile os
Writes data to a file, creating it if it does not exist.
os.WriteFile("out.txt", data, 0644)
os.Getenv os
Returns the value of an environment variable, or empty string if not set.
home := os.Getenv("HOME")
os.Stderr os
An *os.File connected to standard error. Used to write error messages separately from normal output.
fmt.Fprintln(os.Stderr, "error:", err)
os.Stdout os
An *os.File connected to standard output. The destination for fmt.Println and similar functions.
fmt.Fprintln(os.Stdout, "ok")
os.Stdin os
An *os.File connected to standard input. Used to read data typed by the user.
fmt.Fscan(os.Stdin, &x)
os.Mkdir os
Creates a single directory with the given name and permission bits.
os.Mkdir("data", 0755)
os.MkdirAll os
Creates a directory and all necessary parent directories.
os.MkdirAll("a/b/c", 0755)
os.Remove os
Deletes a file or empty directory.
os.Remove("tmp.txt")
os.Stat os
Returns file metadata (size, permissions, modification time) or an error if file does not exist.
info, err := os.Stat("file.txt")
strings package
Functions for manipulating UTF-8 encoded strings: searching, splitting, replacing, trimming, and converting.
import "strings"
strings.Contains strings
Reports whether a substring is present within a string.
strings.Contains("hello world", "world")
strings.Split strings
Splits a string around a separator and returns a slice of substrings.
parts := strings.Split("a,b,c", ",")
strings.Join strings
Concatenates a slice of strings with a separator between each element.
strings.Join([]string{"a","b"}, "-")
strings.TrimSpace strings
Removes leading and trailing whitespace (spaces, tabs, newlines) from a string.
strings.TrimSpace("  hello  ")
strings.Trim strings
Removes leading and trailing characters that appear in the cutset string.
strings.Trim("!!!hi!!!", "!")
strings.HasPrefix strings
Reports whether the string begins with the given prefix.
strings.HasPrefix("golang", "go")
strings.HasSuffix strings
Reports whether the string ends with the given suffix.
strings.HasSuffix("file.go", ".go")
strings.ReplaceAll strings
Returns a copy of the string with all occurrences of old replaced by new.
strings.ReplaceAll(s, " ", "_")
strings.ToLower strings
Returns the string with all letters converted to lowercase.
strings.ToLower("HELLO")
strings.ToUpper strings
Returns the string with all letters converted to uppercase.
strings.ToUpper("hello")
strings.Index strings
Returns the index of the first occurrence of a substring, or -1 if not found.
strings.Index("hello", "ll")
strings.Count strings
Counts non-overlapping occurrences of a substring in a string.
strings.Count("cheese", "e")
strings.Fields strings
Splits a string at any whitespace and returns a slice of words.
strings.Fields("  foo bar  ")
strings.Builder strings
An efficient type for building strings incrementally using WriteString, WriteByte, or WriteRune.
var b strings.Builder; b.WriteString("hello")
strings.EqualFold strings
Case-insensitive string comparison.
strings.EqualFold("Go", "go")
strconv package
Converts between strings and basic data types (int, float, bool). Essential for parsing command-line input.
import "strconv"
strconv.Atoi strconv
Converts a decimal string to an int. Returns the integer and an error.
n, err := strconv.Atoi("42")
strconv.Itoa strconv
Converts an int to its decimal string representation.
s := strconv.Itoa(42)
strconv.ParseFloat strconv
Converts a string to a float64. Returns the value and an error.
f, err := strconv.ParseFloat("3.14", 64)
strconv.ParseInt strconv
Converts a string in the given base (2-36) to an int64. Returns the value and an error.
n, err := strconv.ParseInt("FF", 16, 64)
strconv.ParseBool strconv
Converts strings like "1", "true", "0", "false" to a bool.
b, err := strconv.ParseBool("true")
strconv.FormatInt strconv
Converts an int64 to a string in the specified base (2 for binary, 16 for hex).
strconv.FormatInt(255, 16)
math package
Mathematical functions and constants. All functions operate on float64.
import "math"
math.Abs math
Returns the absolute value of x.
math.Abs(-3.14)
math.Sqrt math
Returns the square root of x.
math.Sqrt(16.0)
math.Pow math
Returns x raised to the power y.
math.Pow(2, 10)
math.Round math
Returns the nearest integer to x, rounding half away from zero.
math.Round(3.6)
math.Floor math
Returns the greatest integer value less than or equal to x.
math.Floor(3.9)
math.Ceil math
Returns the least integer value greater than or equal to x.
math.Ceil(3.1)
math.Log math
Returns the natural logarithm (base e) of x.
math.Log(2.71828)
math.Pi math
The mathematical constant pi = 3.14159265358979...
circumference := 2 * math.Pi * r
math.Mod math
Returns the floating-point remainder of x/y.
math.Mod(7.5, 3.0)
math.Min math
Returns the smaller of x or y.
math.Min(3.0, 5.0)
math.Max math
Returns the larger of x or y.
math.Max(3.0, 5.0)
io package
Defines core I/O interfaces (io.Reader, io.Writer, io.Closer) used throughout the standard library.
import "io"
io.EOF io
The error returned by a reader when there is no more data to read. Signals normal end of input.
if err == io.EOF { break }
io.ReadAll io
Reads from an io.Reader until EOF and returns all the data as a byte slice.
data, err := io.ReadAll(r)
bufio package
Buffered I/O. Wraps io.Reader/Writer with a buffer for efficient line-by-line reading.
import "bufio"
bufio.NewScanner bufio
Creates a Scanner that reads from an io.Reader line by line.
scanner := bufio.NewScanner(os.Stdin)
flag package
Parses command-line flags (e.g., -verbose, -port=8080).
import "flag"
flag.String flag
Defines a string flag. Returns a *string that holds the parsed value.
name := flag.String("name", "world", "who to greet")
flag.Int flag
Defines an integer flag. Returns a *int that holds the parsed value.
port := flag.Int("port", 8080, "listen port")
flag.Bool flag
Defines a boolean flag. Returns a *bool. Set by passing -flag on the command line.
verbose := flag.Bool("verbose", false, "verbose output")
flag.Parse flag
Parses the command-line flags. Must be called after all flags are defined.
flag.Parse()
log package
Simple logging to stderr with timestamp. log.Fatal stops the program after logging.
import "log"
log.Fatal log
Logs a message then calls os.Exit(1). Use for unrecoverable startup errors.
log.Fatal("database connection failed")
log.Println log
Logs a message to stderr with a timestamp and newline.
log.Println("server started")
log.Printf log
Logs a formatted message to stderr with a timestamp.
log.Printf("port: %d", port)
errors package
Functions for creating and inspecting error values.
import "errors"
errors.New errors
Creates a new error with the given message text.
errors.New("invalid input")
errors.Is errors
Reports whether any error in the chain matches the target error.
errors.Is(err, os.ErrNotExist)
sort package
Functions for sorting slices and user-defined collections.
import "sort"
sort.Ints sort
Sorts a slice of ints in ascending order in-place.
sort.Ints(nums)
sort.Strings sort
Sorts a slice of strings in ascending alphabetical order in-place.
sort.Strings(names)
sort.Slice sort
Sorts a slice using a custom less function. Flexible for any type.
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
sync.Mutex sync
A mutual exclusion lock. Use Lock/Unlock to protect shared data from concurrent access.
var mu sync.Mutex; mu.Lock(); mu.Unlock()
sync.WaitGroup sync
Waits for a collection of goroutines to finish. Use Add, Done, and Wait.
var wg sync.WaitGroup; wg.Add(1); wg.Wait()
time.Now time
Returns the current local time as a time.Time value.
now := time.Now()
time.Sleep time
Pauses the current goroutine for at least the specified duration.
time.Sleep(2 * time.Second)
time.Since time
Returns the elapsed time since t.
elapsed := time.Since(start)
goroutine concept
A lightweight thread managed by the Go runtime. Launched with the go keyword. Thousands can run simultaneously.
go worker(jobs)
channel concept
A typed pipe for communication between goroutines. Values are sent and received using the <- operator.
ch := make(chan int, 10)
closure concept
A function that captures variables from its surrounding scope. Useful for callbacks and goroutines.
adder := func(x int) int { return x + n }
pointer concept
A variable that stores the memory address of another value. Declared with * and created with & or new.
p := &x; *p = 42
slice concept
A dynamically-sized view into an array. Has a length, capacity, and a reference to an underlying array.
nums := []int{1, 2, 3}
method concept
A function with a receiver argument. Defined on a type. Called with dot notation: value.Method().
func (p Point) String() string { }
zero value concept
The default value of a variable when none is assigned: 0 for numbers, empty string for strings, false for bools, nil for references.
var n int
type assertion concept
Extracts the concrete type from an interface value. Returns the value and a bool indicating success.
n, ok := i.(int)
variadic concept
A function that accepts a variable number of arguments, declared with ... before the type.
func sum(nums ...int) int { }
main concept
The entry point of a Go program. Must be in package main. Execution starts here.
func main() { fmt.Println("hello") }
go build tool
Compiles Go source files into a binary executable.
go build -o app .
go run tool
Compiles and immediately runs a Go program without creating a persistent binary.
go run main.go
go test tool
Runs tests in the current package. Test functions must start with Test and accept *testing.T.
go test ./...
go mod tool
Manages Go module dependencies. go mod tidy removes unused deps and adds missing ones.
go mod tidy
filepath.Join filepath
Joins any number of path elements into a single path, using the OS separator.
filepath.Join("home", "user", "file.txt")
filepath.Base filepath
Returns the last element of a path (the filename).
filepath.Base("/home/user/file.txt")
filepath.Dir filepath
Returns all but the last element of a path (the directory).
filepath.Dir("/home/user/file.txt")
filepath.Walk filepath
Walks a directory tree, calling a function for each file and directory.
filepath.Walk(".", func(path string, info os.FileInfo, err error) error { return nil })
http.HandleFunc net/http
Registers a handler function for the given URL pattern in the default mux.
http.HandleFunc("/", indexHandler)
http.ListenAndServe net/http
Starts an HTTP server on the given address. Blocks until the server stops.
http.ListenAndServe(":8080", nil)
json.Marshal json
Converts a Go value into a JSON-encoded byte slice.
data, err := json.Marshal(user)
json.Unmarshal json
Parses JSON-encoded data and stores the result in the value pointed to by v.
json.Unmarshal(data, &user)
struct tags json
Annotations on struct fields that control JSON key names and options like omitempty.
Name string `json:"name,omitempty"`