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