Skip to content

Topic archive

Go

Go, also known as Golang, is a statically typed programming language designed at Google for simplicity, fast compilation, efficient execution, and practical concurrency. It is widely used for backend services, cloud tooling, networking software, and command-line applications.

179 articles
Go 13 Sep 2026 4 min read

Remove Slice Ranges with slices.Delete in Go

slices.Delete removes one contiguous range from a slice and shifts the remaining suffix toward the front. The operation modifies the supplied backing storage, so its returned slice header is part of the result rather than an optional convenience. Its signature accepts any slice element type: func Delete[S ~[]E, E any](s S, i, j int) S The half-open interval s[i:j] follows ordinary Go slicing rules. Elements at indices from i through j-1 are removed, while elements before i retain their positions.

Go 13 Sep 2026 3 min read

Remove Prefixes with strings.CutPrefix in Go

Prefix removal often carries two pieces of information: the remaining text and whether the expected prefix was present. strings.CutPrefix represents both results in one operation instead of separating a prefix test from the removal that follows it. That distinction matters when an unchanged string is a valid result. strings.TrimPrefix returns the input unchanged when the prefix is absent, so its return value alone cannot report presence. strings.CutPrefix returns the remainder plus a boolean that preserves that fact explicitly.

Go 13 Sep 2026 4 min read

Remove Explicit Suffixes with strings.CutSuffix in Go

strings.CutSuffix removes one exact trailing string and reports whether that suffix was present. The boolean result is the key distinction from operations that only return transformed text: callers can keep suffix recognition separate from the remaining content. base, found := strings.CutSuffix(name, ".json") If name ends in .json, base contains the preceding text and found is true. Otherwise, base is the original string and found is false. The operation does not scan for a matching fragment in the middle and does not repeatedly strip the suffix.

Go 13 Sep 2026 4 min read

Remove Adjacent Duplicates with slices.Compact in Go

slices.Compact removes repeated values only when they occur next to each other. That detail makes it different from set-based deduplication: the function collapses equal runs, preserves their order, and modifies the supplied slice storage. The operation fits data that is already grouped by value, including sorted slices and streams that naturally produce repeated adjacent states. It does not search the full slice for every matching value. Compact collapses consecutive runs The generic signature accepts slices whose element type is comparable:

Go 13 Sep 2026 4 min read

Partition Go Slices Lazily with slices.Chunk

Batching a slice often starts as index arithmetic: advance by a fixed width, clamp the final boundary, and pass each sub-slice onward. Go 1.23 added slices.Chunk, which expresses that operation as an iterator while preserving the backing storage of the source slice. Its behavior has one detail that matters beyond syntax: every yielded chunk has its capacity clipped to its length. A caller can modify elements through a chunk, but a plain append cannot grow that chunk into the next region of the source slice.

Go 13 Sep 2026 4 min read

Limit Slice Capacity with slices.Clip in Go

A Go slice can expose more capacity than its current length. slices.Clip removes that spare capacity from the slice header, setting capacity to length without copying the elements into new storage. The operation is deliberately narrow. It changes the range that a later append can reuse through that slice value, but it does not release the backing array or create an independent copy. Clip is a full slice expression The standard library defines Clip with this signature:

Go 13 Sep 2026 5 min read

Insert Slice Values with slices.Insert in Go

slices.Insert places one or more values at a specific slice index and shifts the existing suffix to make room. The operation modifies slice storage when possible, but it can also return a slice backed by a new array when existing capacity cannot hold the expanded result. Its generic signature is: func Insert[S ~[]E, E any](s S, i int, v ...E) S The returned slice must replace the previous slice value because insertion changes the length and can change the backing array.

Go 13 Sep 2026 4 min read

Grow Slice Capacity with slices.Grow in Go

slices.Grow reserves room for future appends without changing a slice’s length. The distinction between length and capacity is central to its contract: existing elements remain the logical contents, while the returned slice can accept at least a requested number of additional elements without another allocation. The generic signature is: func Grow[S ~[]E, E any](s S, n int) S The return value matters because increasing capacity can require a new backing array.

Go 13 Sep 2026 3 min read

Find the First Predicate Match with slices.IndexFunc in Go

slices.IndexFunc scans a slice from the beginning and returns the index of the first element accepted by a predicate. That contract is narrower than filtering: only one position is requested, and the scan has no reason to continue after a match. Its standard-library signature accepts any slice element type: func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int The predicate receives each element in index order. A true result ends the search and produces that index. If every call returns false, the function returns -1.

Go 13 Sep 2026 4 min read

Filter Slice Values with slices.DeleteFunc in Go

slices.DeleteFunc removes elements selected by a predicate and compacts the retained values into the same slice storage. It is a filtering operation with mutation semantics: retained order stays intact, the returned slice can be shorter, and callers must use that returned slice header. The generic signature accepts any slice element type: func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S The predicate describes deletion rather than retention. An element disappears when del returns true.

Go 13 Sep 2026 4 min read

Filter a Slice In Place with slices.DeleteFunc in Go

Filtering a Go slice often starts as a small loop that keeps selected elements and discards the rest. slices.DeleteFunc expresses the inverse operation directly: a predicate marks elements for removal, the retained elements stay in their original order, and the existing backing array is reused. That last property matters. DeleteFunc is not a copying filter. It mutates the supplied slice storage and returns a slice header with the resulting length.

Go 13 Sep 2026 4 min read

Copy Slice Storage with slices.Clone in Go

A slice assignment copies a slice header, not its elements. After b := a, both slice values can still refer to the same backing array, so an element update through one value can appear through the other. slices.Clone provides a compact standard-library operation for the cases that need a copy of the slice elements instead. The function is part of the slices package. Its result has the same length as the input and contains the same elements, but later replacement of an element in one slice does not replace the corresponding element in the other.

Go 13 Sep 2026 4 min read

Compare Slices with Custom Equality in Go

slices.EqualFunc compares two slices position by position while leaving the definition of equality to a supplied function. That makes the operation useful when plain == is unavailable or does not express the relation the program needs. The function also permits the two slices to have different element types: func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any]( s1 S1, s2 S2, eq func(E1, E2) bool, ) bool The result still describes sequence equality. Length, order, and every corresponding pair matter.

Go 13 Sep 2026 4 min read

Compact Adjacent Slice Values with slices.CompactFunc in Go

slices.CompactFunc removes repeated values only when equivalent elements are adjacent. That detail makes it distinct from general deduplication: the function operates on runs, keeps the first element from each run, and leaves separated matches alone. The custom equality function also allows compaction for structs and for equivalence rules that differ from Go’s == operator. Compaction is based on neighboring values The function has this signature: func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S For each run in which neighboring elements satisfy eq, the first element remains in the result. Consider case-insensitive string comparison:

Go 13 Sep 2026 4 min read

Combine Slices with slices.Concat in Go

Concatenating several slices with repeated append calls can make ownership depend on spare capacity in the destination. slices.Concat takes a different contract: it returns a new slice containing all input elements in order. That makes the storage boundary explicit when a combined result must stand apart from its inputs. Added in Go 1.22, slices.Concat also defines the empty case precisely. If the total concatenation has no elements, the result is nil, even when one or more arguments are non-nil empty slices.

Go 13 Sep 2026 4 min read

Bound HTTP Request Bodies with http.MaxBytesReader in Go

An HTTP handler that decodes a request body without a byte limit can consume far more input than its application-level schema suggests. A JSON object with three fields may still arrive inside a multi-gigabyte body. Decoder validation controls structure; it does not establish a transport-sized boundary. Go’s http.MaxBytesReader places that boundary directly around the request body. It returns an io.ReadCloser that permits reads up to a configured limit and reports an error when code attempts to read beyond it.

Go 12 Sep 2026 4 min read

Traverse Slices in Reverse with slices.Backward in Go

Reverse traversal does not require reversing a slice. Since Go 1.23, slices.Backward exposes the existing elements as an iterator that emits index-value pairs from the last element toward index zero. That distinction matters when element order must stay intact. slices.Reverse changes the slice in place, while a hand-written descending loop couples traversal to index arithmetic. slices.Backward expresses reverse iteration without changing the source. The iterator keeps original indexes The function has this signature:

Go 12 Sep 2026 4 min read

Track Goroutine Lifetimes with sync.WaitGroup.Go in Go

sync.WaitGroup.Go combines goroutine creation with task accounting. Added in Go 1.25, the method removes a small but consequential gap between incrementing a wait-group counter and starting the goroutine that will eventually decrement it. The method does not change what a WaitGroup represents. It still tracks a set of tasks and lets another goroutine block until that set is complete. The difference is that registration and goroutine launch now share one operation.

Go 12 Sep 2026 7 min read

Sort Go Struct Slices with slices.SortFunc

Sorting a slice of structs usually starts with a field: priority, timestamp, name, score, or some combination of them. slices.Sort can’t handle a struct because a struct has no built-in ordering relation. slices.SortFunc fills that gap by taking a comparator that defines the order for the element type. The call is compact, but the comparator is part of the program’s correctness. It has to describe a consistent ordering, and equal comparisons need deliberate handling when records have multiple fields. This article builds that comparator from simple cases to multi-field ordering and covers the mutation and stability details that tend to cause surprises.

Go 12 Sep 2026 6 min read

Sort Go Slices in Place with slices.Sort

A slice arrives out of order, and all you need is ascending numbers or strings. You don’t need a comparator or a wrapper type for that case. slices.Sort handles ordered element types directly and changes the existing slice into ascending order. That directness is useful, but the in-place behavior deserves attention. Sorting a slice can also change what another slice sees when both share the same backing array. This article covers the straightforward call first, then the details that matter once slices move between functions and components.

Go 12 Sep 2026 6 min read

Search Sorted Go Slices with slices.BinarySearch

Searching a slice often starts with a loop, and for unsorted data that can be the right choice. When the slice is already sorted, slices.BinarySearch gives you a more specific operation: it finds a target without scanning every element from the beginning, and it also tells you where a missing target belongs in the current order. That second result is easy to overlook. It makes the function useful not only for membership checks, but also for maintaining sorted collections without writing separate insertion-point logic.

Go 12 Sep 2026 5 min read

Run Cancellation Callbacks with context.AfterFunc in Go

context.AfterFunc attaches a callback to context cancellation without adding a goroutine that waits only on ctx.Done(). When the context becomes done, the callback starts in its own goroutine. The small API hides a concurrency boundary that matters when the callback mutates shared state, interrupts blocking I/O, or competes with normal completion. The function arrived in Go 1.21 and returns a stop function. That return value is not a general cancellation handle for the callback. It controls the association between the context and the callback, with precise behavior once cancellation and callback startup begin to race.

Go 12 Sep 2026 4 min read

Repeat Slice Patterns in Go with slices.Repeat

Repeated slice patterns show up in test fixtures, cyclic configuration data, padding schemes, and small generated sequences. slices.Repeat handles that shape directly: it returns a new slice containing the input sequence repeated a specified number of times. The result has a defined size and separate slice storage. Its boundary cases also matter, especially when the repeat count comes from external input or arithmetic. Build a repeated pattern with slices.Repeat A count of three copies the complete input sequence three times:

Go 12 Sep 2026 6 min read

Remove a Range from Go Slices with slices.Delete

Removing one or more adjacent elements from a Go slice used to mean writing the reslicing and append expression by hand. slices.Delete gives that operation a direct name and handles the vacated tail slots for you. The call uses the same half-open range convention as slicing: slices.Delete(s, i, j) removes indexes i through j-1. The returned slice is shorter, so keep the return value. Remove a range with slices.Delete A basic deletion looks like this: