Skip to content

Archive

Go

100 articles
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 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:

Go 12 Sep 2026 5 min read

Reject Cross-Origin State Changes with http.CrossOriginProtection

A browser can send credentials with a request that was initiated from another site. For state-changing endpoints, accepting that request without checking its origin can expose an application to cross-site request forgery. Go’s net/http package includes CrossOriginProtection for placing that check at an HTTP handler boundary. The type does not attempt to identify every browser request. It applies a specific policy based on request method and cross-origin signals, while allowing requests that lack those browser-origin signals. Its behavior is narrow enough that endpoint semantics still matter.

Go 12 Sep 2026 6 min read

Preserve Equal-Item Order in Go with slices.SortStableFunc

A sort can produce the correct key order and still damage information you meant to keep. Suppose records already arrive in creation order, and the UI groups them by status. If records with the same status should remain in creation order, an unstable sort doesn’t provide the contract you need. slices.SortStableFunc handles that case. It sorts with a custom comparator and preserves the original relative order of elements that the comparator treats as equal.

Go 12 Sep 2026 4 min read

Merge Map Entries with maps.Copy in Go

Merging two Go maps often comes down to one precise rule: entries from one map are assigned into another, and matching keys replace existing destination values. maps.Copy gives that operation a standard-library form without changing its underlying assignment semantics. The function mutates the destination map. It does not allocate a replacement, return a merged value, or recursively copy data stored behind pointers, slices, maps, or other reference-bearing values. Source entries overwrite matching destination keys maps.Copy accepts a destination followed by a source. Every source pair is assigned to the destination. Keys that exist only in the destination remain present.

Go 12 Sep 2026 5 min read

Materialize Iterator Values with slices.Collect in Go

An iter.Seq can produce values without storing them all at once. That representation is useful while values are flowing through iterator-based code, but many APIs still need an ordinary slice. Since Go 1.23, slices.Collect provides that materialization boundary directly. The function consumes a one-value sequence and returns a newly built slice containing each yielded value in sequence order. It is small API surface, but its allocation, ownership, and empty-input behavior are useful to make explicit.

Go 12 Sep 2026 4 min read

Limit Go Slice Capacity with slices.Clip

A Go slice can be short while still carrying much more capacity than its current length. That extra capacity is useful when more elements are expected, but sometimes code should hand off a slice without leaving room for an append to reuse the same tail. slices.Clip gives that intent a direct operation. Clip returns a slice with the same elements and length, but its capacity is reduced to its length.

Go 12 Sep 2026 4 min read

Iterate Fixed-Size Slice Groups with slices.Chunk in Go

Splitting a slice into bounded groups often starts as index arithmetic: advance by a fixed width, clamp the final boundary, and take a sub-slice. Go 1.23 puts that operation in the standard library as slices.Chunk. Chunk returns an iterator rather than a [][]T. That detail keeps grouping separate from collecting, and its capacity rule gives each yielded group a useful boundary for later append calls. Chunk produces consecutive sub-slices The signature is:

Go 12 Sep 2026 4 min read

Filter Map Entries in Place with maps.DeleteFunc

Filtering a Go map often means removing entries from an existing map rather than allocating a replacement. maps.DeleteFunc expresses that operation directly: it visits entries and deletes each pair for which a predicate returns true. That mutation model is the central detail. The function does not return a filtered copy, and callers that share the same map observe the deletions. The predicate receives both key and value maps.DeleteFunc accepts a map and a function with the key and value types of that map. A compact filter can use either argument or both:

Go 12 Sep 2026 5 min read

Compare Map Values with maps.EqualFunc in Go

Two Go maps can represent the same logical data even when their value types differ or their values need domain-specific comparison. maps.EqualFunc handles that case by matching keys normally while delegating value comparison to a caller-supplied function. That split matters. The comparator controls value equivalence only. It cannot redefine key identity, compensate for a missing key, or make maps with different entry counts equal. Key membership is checked before value equivalence The function accepts two maps with the same key type but potentially different value types:

Go 12 Sep 2026 6 min read

Compare Go Slices with Custom Rules Using slices.CompareFunc

Two slices can represent the same ordered data even when their element types differ. One side might contain integers while another contains numeric strings, or two struct types might expose the same key through different fields. Plain slices.Compare can’t express those cases because it relies on the element type’s built-in ordering. slices.CompareFunc lets you supply the element comparison. It still compares the slices lexicographically, so the first unequal pair decides the result; the custom function only defines how each pair is ordered.

Go 12 Sep 2026 4 min read

Clone Go Maps with maps.Clone

A Go map variable refers to mutable map state. Assigning that variable to another variable does not create an independent map: writes through either name affect the same map. When code needs a separate top-level map with the same entries, maps.Clone makes that boundary explicit. The function is deliberately narrow. It copies map entries using ordinary assignment. The resulting map can be changed independently at the key-value entry level, but reference-like data stored inside keys or values can still share underlying state.

Go 12 Sep 2026 5 min read

Check Custom Slice Order in Go with slices.IsSortedFunc

Code that depends on binary search, ordered output, or merge-style processing often assumes a slice is already sorted. For built-in ordered values, slices.IsSorted can check that assumption. Structs and domain-specific orderings need a comparator, which is where slices.IsSortedFunc fits. The function doesn’t rearrange anything. It answers a narrower question: does this slice already follow the order described by this comparator? Check a struct slice by one field slices.IsSortedFunc accepts a slice and a comparison function:

Go 11 Sep 2026 6 min read

Sort Struct Slices in Go with slices.SortFunc

Sorting a slice of structs usually starts with a simple requirement such as “priority first, then ID.” The awkward part is expressing that ordering clearly enough that sorting, validation, and binary search can all agree on it. slices.SortFunc handles this directly. You give it the slice and a comparator that defines the order. It sorts the existing slice in place, so there is no separate result to assign. Sort a struct slice with slices.SortFunc Suppose a queue contains jobs that should be ordered by ascending priority and then by ID when priorities match:

Go 11 Sep 2026 7 min read

Sort Iterator Values Stably in Go with slices.SortedStableFunc

An iterator can produce values in an order that already means something: arrival order, file order, database order, or the order established by an earlier stage of a pipeline. If you need to sort those values by one key without scrambling equal-key groups, slices.SortedStableFunc handles both steps at once. It consumes an iter.Seq, collects the yielded values into a new slice, and sorts that slice with a comparator. When the comparator returns zero, the values keep the same relative order they had in the sequence.

Go 11 Sep 2026 5 min read

Reverse Go Slices in Place with slices.Reverse

Sometimes the order stored in a slice needs to change, not just the order in which code visits its elements. A queue may need newest-first presentation, a collected path may need to run from origin to destination, or a stack snapshot may need its top element first. slices.Reverse handles that edit directly. The key detail is mutation. slices.Reverse rearranges the existing slice in place. It doesn’t return a replacement slice, and code sharing the same backing array can observe the new order.

Go 11 Sep 2026 5 min read

Reserve Go Slice Capacity with slices.Grow

Repeated append calls can force a Go slice to move to a larger backing array when its capacity runs out. If code already knows that several more elements are about to arrive, slices.Grow can reserve enough room before those appends happen. The key detail is that slices.Grow changes capacity when needed, not length. Existing elements stay in place logically, and the returned slice still contains the same number of elements.

Go 11 Sep 2026 5 min read

Replace a Range in Go Slices with slices.Replace

Replacing part of a slice often starts as an append expression that works but takes a moment to decode. slices.Replace gives that operation a direct name: choose the half-open range s[i:j], provide replacement values, and keep the returned slice. The replacement doesn’t have to be the same size as the removed range. It can be shorter, longer, or empty, which makes slices.Replace useful for more than one-for-one edits. Replace a slice range with slices.Replace The basic call replaces every element from index i up to, but not including, index j:

Go 11 Sep 2026 4 min read

Remove Adjacent Duplicates from Go Slices with slices.Compact

Duplicate values often arrive in runs: repeated status events, sorted IDs, or adjacent tokens produced by a parser. When only consecutive duplicates need to disappear, slices.Compact handles the operation without a handwritten loop. The distinction is specific. slices.Compact collapses adjacent equal values; it doesn’t search the entire slice for duplicates. It also modifies the slice’s backing storage, so callers need to account for aliasing. Remove adjacent duplicates with slices.Compact Pass a slice whose element type is comparable and assign the returned slice:

Go 11 Sep 2026 6 min read

Remove a Range from Go Slices with slices.Delete

Removing a known range from a Go slice is easy to express with slices.Delete. Give it the slice and a half-open index range, and it closes the gap for you. The small details matter. slices.Delete changes the slice’s contents, returns a slice with a new length, and panics for an invalid range. Using it well means treating those behaviors as part of the operation rather than as implementation trivia. Remove a range with slices.Delete Suppose a pipeline contains stages that are no longer needed:

Go 11 Sep 2026 5 min read

Preserve Equal Element Order in Go with slices.SortStableFunc

Sometimes sorting by one field is only half the requirement. You may want jobs grouped by priority while keeping their arrival order inside each priority, or records grouped by category without disturbing an earlier ranking. slices.SortStableFunc is built for that case. It sorts a slice in place using a custom comparator, but elements that compare equal keep their original relative order. Preserve equal elements with slices.SortStableFunc Suppose jobs arrive in this order:

Go 11 Sep 2026 5 min read

Iterate Go Map Values with maps.Values

Sometimes a Go map’s keys are irrelevant to the next operation. You may need to total counters, inspect status values, or pass the values into an iterator-aware helper. A plain map range works well inside one loop, but it doesn’t give you a value sequence that can cross an API boundary. Since Go 1.23, maps.Values returns an iter.Seq over a map’s values. That lets code consume values directly and postpone slice allocation until a later operation actually needs a slice.

Go 11 Sep 2026 4 min read

Iterate Go Map Pairs with maps.All

A normal range loop is often the clearest way to walk through a Go map. The situation changes when another API expects an iterator rather than a map. Starting in Go 1.23, maps.All provides that bridge by exposing a map’s key-value pairs as an iter.Seq2. maps.All doesn’t copy the map into a slice or build a second map. It returns an iterator that can feed a range loop or another iterator-aware function. The main constraint is familiar from map iteration: pair order is unspecified.