Go examples
20 runnable Go examples — every snippet executes on the real CompileBytes engine, right on the page. Copy it, edit it, and run it again. No setup or signup.
How to reverse a string in Go
Reverse a string in Go the Unicode-safe way — []rune plus a two-pointer swap, slices.Reverse, and strings.Builder — plus why reversing []byte corrupts non-ASCII text.
How to convert a string to an int in Go
Convert a string to an int in Go with strconv.Atoi — plus ParseInt for hex, binary, and bit sizes, ParseFloat for decimal strings, and how to handle bad input and overflow the idiomatic way.
How to check if a key exists in a map in Go
Check if a key exists in a Go map with the comma-ok idiom — v, ok := m[key] — plus the zero-value trap, existence-only sets with map[string]struct{}, value lookups, and how nil maps behave.
How to check if a slice contains an element in Go
Check if a Go slice contains a value with slices.Contains (Go 1.21+), the classic loop for older code, slices.ContainsFunc for custom matches, slices.Index when you need the position, and a map set for repeated lookups.
How to sort a slice in Go
Sort a Go slice with slices.Sort (Go 1.21+), order structs and custom keys with slices.SortFunc and cmp.Compare, sort.Slice for older code, stable multi-key sorts, and how to sort without mutating the original.
How to remove an element from a slice in Go
Remove an element from a Go slice with slices.Delete (Go 1.21+), the classic append(s[:i], s[i+1:]...) idiom, O(1) swap-with-last removal when order does not matter, slices.DeleteFunc for bulk filtering, and the aliasing trap that leaks memory.
How to check if a string contains a substring in Go
Check whether a Go string contains a substring with strings.Contains — plus HasPrefix/HasSuffix for anchored checks, ContainsAny and ContainsRune for character sets, Index when you need the position, and how to search case-insensitively when there is no ContainsFold.
How to split a string in Go
Split a string in Go with strings.Split — plus strings.Fields for whitespace, SplitN to cap the pieces, strings.Cut for key=value, bufio.Scanner for lines, and FieldsFunc/regexp for several delimiters at once.
How to concatenate strings in Go
Concatenate strings in Go with + for a couple of pieces, strings.Builder inside a loop, and strings.Join for a []string — plus fmt.Sprintf for formatting, bytes.Buffer for byte output, and why += in a loop is O(n²).
How to trim whitespace from a string in Go
Trim whitespace from a string in Go with strings.TrimSpace — plus custom cutsets with Trim, the TrimLeft-vs-TrimPrefix trap, TrimFunc for zero-width characters, and collapsing inner whitespace with Fields + Join.
How to convert an int to a string in Go
Convert an int to a string in Go with strconv.Itoa — plus FormatInt for other bases, fmt.Sprintf for padded output, why string(65) gives "A" not "65", and how to build strings from many ints without O(n²) concatenation.
How to iterate over a map in Go
Iterate over a Go map with for k, v := range m — plus keys-only and values-only loops, why the iteration order is deliberately randomised, how to get a stable order with slices.Sorted(maps.Keys(m)), sorting by value, and what is legal to change while the loop runs.
How to remove a key from a map in Go
Remove a key from a Go map with the delete builtin — plus why deleting a missing key is a safe no-op, deleting while ranging, clear() vs make() vs nil, and why delete never gives the memory back.
How to remove duplicates from a slice in Go
Remove duplicates from a Go slice with a map[T]struct{} seen-set that preserves first-seen order, or slices.Sort + slices.Compact when sorted output is fine — plus CompactFunc for case-insensitive dedupe, deduping structs by a key field, and the zero-allocation s[:0] filter.
How to loop with an index in Go
Loop with an index in Go — for i, v := range s, the index-only and value-only forms, the classic three-clause loop for backwards and custom steps, why ranging a string gives byte offsets, and the Go 1.22 loop-variable change.
How to convert a struct to JSON in Go
Turn a Go struct into JSON with json.Marshal — plus struct tags for key names, omitempty and hidden fields, MarshalIndent for pretty output, nested structs, maps and time.Time, and streaming with json.Encoder.
How to parse JSON into a struct in Go
Parse JSON into a Go struct with json.Unmarshal — struct tags and field matching, JSON arrays and nested objects, map[string]any for unknown payloads, pointer fields to tell missing from zero, and json.Decoder for strict parsing.
How to format a date in Go
Format a date in Go with t.Format and the reference-time layout "2006-01-02 15:04:05" — why it is that date, the predefined layouts like time.RFC3339 and time.DateOnly, parsing back with time.Parse, 12-hour clocks and padding, and time zones.
How to wait for goroutines to finish in Go
Wait for goroutines to finish in Go with sync.WaitGroup — Add, Done and Wait — plus why a bare go f() prints nothing, how to collect results without a data race, mutex and atomic counters, channel fan-in, and errgroup-style error handling with only the standard library.
How to handle errors in Go
Handle errors in Go the idiomatic way — check err != nil and return early, add context with fmt.Errorf and %w, match sentinels with errors.Is, pull typed errors out with errors.As, join several failures with errors.Join, and know when panic/recover is the wrong tool.
Same task, different syntax
Examples in other languages
Compare how familiar programming tasks look across the catalog.
FAQ
Go examples, explained
Can I run the code on this page?+
Yes. Every Go example is a live snippet that runs on the CompileBytes engine. You can edit and rerun it without installing anything.
Is this free? Do I need an account?+
Every example is free to read, run, edit, and copy. No account is required.
Can I copy these into my own projects?+
Yes. These examples are designed to be copied and adapted to your own code.
Where can I run my own code?+
Open the Go compiler from the main playground catalog, then paste or write any code you want to run.