Skip to content

Archive

Standard Library

147 articles
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 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 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 5 min read

Interleave HTTP Request Reads and Response Writes in Go

An HTTP handler that writes its response before finishing the request body has a protocol-sensitive edge case. With HTTP/1, Go’s server normally consumes the unread request body before it begins writing the response. That default keeps ordinary handlers simple, but it conflicts with handlers that intentionally exchange data in both directions at the same time. http.ResponseController.EnableFullDuplex changes that behavior for the current request. It tells the server that the handler intends to interleave reads from Request.Body with writes to the ResponseWriter.

Go 12 Sep 2026 5 min read

Flush Buffered HTTP Data with http.ResponseController in Go

An HTTP handler can write bytes without making those bytes immediately visible to the client. The server, transport, middleware, or another layer may buffer response data. For handlers that emit incremental output, http.ResponseController.Flush provides an explicit request to push buffered data toward the client. The operation belongs to the current response. It does not turn a normal handler into a separate transport protocol, and it does not guarantee that every intermediary on the network will forward each chunk at the same instant. Its useful contract is narrower: ask the active response writer to flush data it has buffered.

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: