Skip to content

Archive

Slices

68 articles
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 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 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 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 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

Insert Values into Go Slices with slices.Insert

Adding a value to the middle of a Go slice takes more work than appending at the end. Elements after the insertion point need to move, and the operation may require a larger backing array. slices.Insert packages that splice into one standard-library call. The function accepts a slice, an index, and one or more values. It returns the resulting slice, so the usual form assigns that result back to the slice variable.

Go 11 Sep 2026 5 min read

Find the Smallest Go Slice Value with slices.Min

Finding the smallest value in a Go slice doesn’t require sorting or a hand-written comparison loop. When the element type has a natural order, slices.Min states the operation directly and leaves the input untouched. The call is compact, but its contract matters at the edges. An empty slice causes a panic, and a floating-point NaN propagates to the result. Those cases are best handled where the application can attach useful meaning to them.

Go 11 Sep 2026 5 min read

Find the Largest Go Slice Value with slices.Max

Finding the largest value in a slice is a small operation, but handwritten loops still create room for awkward initialization and missed empty-input handling. For ordered values such as integers, strings, and floating-point numbers, slices.Max expresses the operation directly. The function scans the slice and returns its maximal element. It doesn’t sort or modify the input. Two details deserve attention in production code: an empty slice causes a panic, and floating-point input containing a NaN produces a NaN result.

Go 11 Sep 2026 5 min read

Find Minimum Struct Values in Go with slices.MinFunc

Finding the smallest number in a slice is straightforward, but real programs often need the cheapest quote, earliest task, shortest route, or lowest-priority struct. Those values aren’t ordered by Go itself, so slices.Min can’t express the rule. slices.MinFunc handles that case. You provide the slice and a comparator; it returns the element that is minimal according to that comparator. What slices.MinFunc does The function accepts slices of any element type:

Go 11 Sep 2026 5 min read

Find Maximum Struct Values in Go with slices.MaxFunc

Finding the largest integer in a Go slice is easy. The problem gets more interesting when the slice contains structs and “largest” means the build with the longest duration, the newest release, or the highest application-specific score. slices.MaxFunc is designed for that case. It scans a slice and returns the maximal element according to a comparator you provide, so the ordering rule can live next to the selection instead of being hidden in a separate sort.

Go 11 Sep 2026 6 min read

Find Exact Values in Go Slices with slices.Index

A slice often holds a short sequence where you need the position of one exact value: a status in a workflow, a command-line argument, a feature name, or an ID in a small ordered list. slices.Index handles that case directly. It returns the first matching index, or -1 when the value isn’t present. That return contract is simple, but it affects how callers should use the result. Indexing the slice before checking for -1 will panic, repeated searches still scan linearly, and exact equality isn’t suitable for every data type or matching rule.

Go 11 Sep 2026 4 min read

Copy Go Slices with slices.Clone

A slice assignment copies the slice header, not its backing array. That detail becomes visible as soon as one variable changes an element and another variable unexpectedly sees the same change. slices.Clone gives the copied slice separate element storage with a single call. The copy is shallow. That makes it a clean fit for slices of numbers, strings, and value-only structs, but nested maps, slices, pointers, and other reference-like values still need deliberate handling.

Go 11 Sep 2026 6 min read

Compare Struct Slices in Go with slices.CompareFunc

Two slices can represent ordered records rather than plain strings or numbers. Maybe they’re deployment steps, semantic-version parts, or structs sorted by a domain-specific key. When you need to answer which sequence comes first, slices.Compare isn’t enough if the elements don’t have Go’s built-in ordering. slices.CompareFunc handles that case. It compares two slices from left to right and lets you define what it means for one pair of elements to be less than, equal to, or greater than the other.