Go Reference
Every Go keyword, built-in, standard library package, command and concept in one place: concise, accurate pages with live examples that compile and run on Go 1.27, with syntax, parameters and return values.
Keywords and Statements
-
packageDeclaring a package and its name. -
importImporting packages, aliases, dot and blank imports. -
varDeclaring variables and zero values. -
:=Short variable declarations and scope pitfalls. -
constConstants, typed and untyped. -
iotaAuto-incrementing constant generator. -
funcDeclaring functions, methods and literals. -
returnReturning values and named results. -
ifConditions and init statements. -
switchExpression switches, fallthrough and tagless switch. -
type switchBranching on a dynamic type. -
selectWaiting on several channel operations. -
forThe only loop: three forms. -
rangeIterating slices, maps, strings, channels, ints and functions. -
breakLeaving loops, switches and selects. -
continueSkipping to the next iteration. -
gotoJumping to a label. -
fallthroughFalling into the next switch case. -
deferDeferred calls and evaluation order. -
goStarting goroutines. -
structStruct types and fields. -
interfaceMethod sets and type sets. -
mapMap types. -
chanChannel types and directions. -
typeDefining types and aliases.
Built-in Functions
-
append()Adding elements to a slice. -
cap()Capacity of slices, arrays and channels. -
clear()Emptying a map or zeroing a slice. -
close()Closing a channel. -
complex(), real(), imag()Building and splitting complex numbers. -
copy()Copying between slices. -
delete()Removing a map entry. -
len()Length of strings, slices, maps, arrays, channels. -
make()Creating slices, maps and channels. -
max() and min()Largest and smallest of several values. -
new()Allocating a zeroed value. -
panic()Starting a panic. -
recover()Stopping a panic inside a deferred call.
Built-in Types
-
int, int8 to int64Signed integers and their ranges. -
uint, uint8 to uint64, uintptrUnsigned integers. -
byte and runeAliases for uint8 and int32. -
float32 and float64Floating-point numbers. -
stringImmutable byte sequences. -
ArraysFixed-length value types. -
SlicesViews over arrays: length, capacity, sharing. -
MapsHash tables and iteration order. -
PointersAddresses and dereferencing. -
ChannelsTyped communication pipes. -
anyAlias for interface{}. -
comparableConstraint for == types. -
Type parametersGeneric functions and types. -
Constraints and ~TType sets and approximation elements.
Operators
-
+ - * / %Arithmetic and integer division. -
== != < <= > >=Comparison rules per type. -
Logical operatorsAND, OR, NOT and short-circuiting. -
Bitwise operatorsAND, OR, XOR and AND NOT. -
<< and >>Shifts and shift-count rules. -
= and op=Assignment and compound assignment. -
& and *Address-of and dereference. -
<-Channel send and receive. -
[] and [:]Indexing and slice expressions. -
x.(T)Type assertions. -
Operator precedencePrecedence table.
fmt Package
-
fmtPackage overview. -
fmt.Println()Print with spaces and a newline. -
fmt.Printf()Formatted output. -
fmt.Sprintf()Format into a string. -
fmt.Fprintf()Format to an io.Writer. -
fmt.Errorf()Wrapping errors with %w. -
fmt.Scan()Reading input values. -
fmt verbs%v, %+v, %#v, %T, %d, %s, %q and more. -
Width, precision and flagsPadding and alignment. -
fmt.StringerCustom String methods.
strings and strconv
-
stringsPackage overview. -
strings.Contains()Substring tests. -
strings.Index()Finding substrings. -
strings.Split()Splitting strings. -
strings.Fields()Splitting on whitespace. -
strings.Join()Joining with a separator. -
strings.Replace()Replacing substrings. -
strings.Trim() familyTrimming characters and affixes. -
strings.ToUpper() and ToLower()Case conversion. -
strings.HasPrefix() and HasSuffix()Affix tests. -
strings.Repeat()Repeating a string. -
strings.Cut()Splitting around a separator. -
strings.BuilderEfficient string building. -
strings.ReplacerMany replacements at once. -
strconvPackage overview. -
strconv.Atoi()String to int. -
strconv.Itoa()Int to string. -
strconv.ParseInt(), ParseFloat(), ParseBool()Parsing with bases and sizes. -
strconv.FormatInt() and FormatFloat()Formatting numbers. -
strconv.Quote() and Unquote()Quoting strings.
bytes, unicode and text
-
bytesByte slice helpers. -
bytes.BufferA growable byte buffer. -
unicodeRune classification. -
unicode.IsLetter(), IsDigit(), IsSpace()Character tests. -
unicode/utf8Decoding and counting UTF-8. -
utf8.RuneCountInString()Counting characters. -
text/templateText templates. -
regexpRegular expressions. -
regexp.Regexp methodsMatch, Find and Replace and Submatch.
Collections: sort, slices, maps
-
sortSorting package. -
sort.Ints(), Strings(), Float64s()Sorting basic slices. -
sort.Slice()Sorting with a less function. -
sort.InterfaceCustom sort types. -
slicesGeneric slice helpers. -
slices.Sort() and SortFunc()Generic sorting. -
slices.Contains() and Index()Searching slices. -
slices.Reverse(), Max(), Min()Common slice operations. -
slices.Insert() and Delete()Editing slices. -
slices.All(), Values(), Collect()Slices and iterators. -
mapsGeneric map helpers. -
maps.Keys() and Values()Iterating keys and values. -
container/list, heap, ringStandard data structures.
Errors, I/O and Files
-
errorsError values. -
errors.New()Creating errors. -
errors.Is()Matching wrapped errors. -
errors.As()Extracting error types. -
errors.Join()Combining errors. -
ioReader and Writer interfaces. -
io.Reader and io.WriterThe core interfaces. -
io.Copy()Streaming between writers and readers. -
io.ReadAll()Reading everything. -
bufioBuffered I/O. -
bufio.ScannerLine and word scanning. -
bufio.Reader and WriterBuffered reads and writes. -
osOperating system access. -
os.ReadFile() and WriteFile()Whole-file I/O. -
os.Open() and Create()Opening files. -
os.Args and os.Getenv()Arguments and environment. -
path/filepathFile path helpers. -
filepath.WalkDir()Walking directory trees. -
io/fsFile-system abstraction. -
embedEmbedding files in binaries. -
os/execRunning commands.
Time, Math and Randomness
-
timeTime package overview. -
time.Now()Current time. -
time.Since() and Until()Measuring elapsed time. -
time.DurationDurations and constants. -
time.Format() and Parse()Layouts and the reference time. -
time.TickerPeriodic events. -
time.After() and NewTimer()Timeouts and timers. -
mathMath functions. -
math.Sqrt() and Pow()Roots and powers. -
math.Floor(), Ceil(), Round()Rounding. -
math/bigBig integers, rationals and floats. -
math/rand/v2Pseudo-random numbers. -
math/bitsBit manipulation.
Concurrency and Context
-
syncSynchronization primitives. -
sync.Mutex and RWMutexMutual exclusion. -
sync.WaitGroupWaiting for goroutines. -
sync.Once, OnceFunc, OnceValueRun once. -
sync.PoolReusing temporary objects. -
sync.MapConcurrent map. -
sync/atomicAtomic operations. -
contextCancellation and deadlines. -
context.WithCancel()Manual cancellation. -
context.WithTimeout() and WithDeadline()Time limits. -
context.WithValue()Request-scoped values. -
runtimeRuntime information and control.
Encoding and Data Formats
-
encoding/jsonJSON package. -
json.Marshal()Value to JSON. -
json.Unmarshal()JSON to value. -
json.Encoder and DecoderStreaming JSON. -
JSON struct tagsomitempty, string, renaming. -
json.RawMessageDelaying decoding. -
encoding/xmlXML. -
encoding/csvCSV. -
encoding/base64Base64. -
encoding/binaryFixed-size binary data. -
crypto/sha256 and md5Hashes. -
crypto/randSecure randomness. -
html/templateContext-aware HTML templates.
Networking and the Web
-
net/httpHTTP package overview. -
http.Get()Simple client request. -
http.ClientTimeouts and transports. -
http.HandleFunc()Registering handlers. -
http.HandlerHandler interface. -
http.ServeMuxRouting and method patterns. -
http.ServerTimeouts and graceful shutdown. -
http.RequestRequest fields. -
http.ResponseWriterWriting responses. -
net/http/httptestTesting handlers. -
net/urlURL parsing and queries. -
netTCP, UDP and listeners. -
database/sqlDatabase interface.
Logging, Flags and Testing
The go Command and Tools
-
go runCompile and run. -
go buildBuilding binaries. -
go installInstalling tools. -
go testRunning tests. -
go vetStatic checks. -
go fmt and gofmtFormatting. -
go modModule management. -
go getAdding dependencies. -
go envEnvironment variables. -
go listPackage metadata. -
go docDocumentation in the terminal. -
go generateCode generation. -
go workWorkspaces. -
go toolpprof, trace, cover. -
Build flags and ldflags-ldflags, -race, -tags. -
Build constraints//go:build lines. -
//go: directives//go:embed, //go:generate, //go:debug.
Concepts
-
Zero valuesDefaults for every type. -
Scope and shadowingBlocks and shadowing pitfalls. -
Exported identifiersCapitalization rules. -
Method setsValue vs pointer receivers. -
Struct embeddingPromotion of fields and methods. -
Nil interface pitfallA non-nil interface holding nil. -
Slice aliasing and appendShared backing arrays. -
Maps and concurrencyWhy concurrent writes panic. -
Loop variable semanticsPer-iteration variables. -
Goroutine leaksCauses and fixes. -
Channel rulesNil, closed and blocked channels. -
Panic and recover rulesWhen to panic. -
Error handling conventionsWrapping, sentinels and types. -
Escape analysisStack vs heap. -
The Go memory modelHappens-before. -
Garbage collectorTuning GOGC and GOMEMLIMIT. -
Generics rulesInference and limits. -
Range-over-func iteratorsPush and pull iterators. -
Type conversionsNumeric and string conversions. -
Strings, bytes and runesUTF-8 in practice.
Nothing matches โโ. Try the site search.