Skip to content

Archive

Slices

68 articles
Go 11 Sep 2026 5 min read

Compare Go Slices for Equality with slices.Equal

Two slices can contain the same number of elements and still represent different sequences. When equality means “same length, same value at every index,” slices.Equal expresses that check directly without a manual loop. The function is small, but a few details matter in production code. Element order counts, nil and empty slices compare equal, element types must be comparable, and floating-point NaN values don’t compare equal to themselves. Compare Go slices with slices.Equal For strings, integers, booleans, and other comparable element types, pass both slices directly:

Go 11 Sep 2026 5 min read

Check Exact Values in Go Slices with slices.Contains

Code often needs a simple membership check: is this status allowed, does this short list contain a requested format, or has this identifier already appeared in a small batch? slices.Contains answers that question directly for comparable values and returns a boolean. The operation is deliberately narrow. It checks exact equality, doesn’t return a position, and scans the slice until it finds a match or reaches the end. Those details make it a good fit for some lookups and a poor fit for others.

Go 11 Sep 2026 6 min read

Check Custom Slice Ordering in Go with slices.IsSortedFunc

Sometimes you need to know whether a slice is already in the right order, not sort it again. That comes up when validating API input, checking an invariant before binary search, or avoiding unnecessary work when records are expected to arrive ordered. For plain numbers and strings, slices.IsSorted handles the common case. When the elements are structs or the ordering is application-specific, slices.IsSortedFunc lets you define exactly what “sorted” means and returns a boolean without rearranging the slice.

Go 10 Sep 2026 5 min read

Sort Go Iterator Values with slices.Sorted

An iter.Seq is convenient while values are flowing through a pipeline. Sorting changes the problem: a sort needs all of those values available at once. If the next step needs an ordered slice, Go has a standard-library helper that makes that boundary explicit. Go 1.23 added slices.Sorted. It consumes an iter.Seq of ordered values, collects the values into a new slice, sorts that slice in ascending order, and returns it.

Go 10 Sep 2026 6 min read

Search Go Struct Slices with slices.BinarySearchFunc

A slice of structs can be sorted by an ID, timestamp, or other field even though the struct itself has no built-in ordering. When you need repeated lookups in that sorted data, slices.BinarySearchFunc lets the search use the same ordering without building a separate index. The comparator is the part that deserves attention. It doesn’t compare two slice elements. It compares one element from the slice with the search target, and its ordering must agree with the way the slice is sorted.

Go 10 Sep 2026 5 min read

Restrict Slice Capacity in Go with slices.Clip

A Go slice can be much smaller than the backing array it refers to. That spare capacity is useful when more append calls are coming, but sometimes you deliberately want the opposite: a result whose capacity stops exactly at its current length. slices.Clip expresses that operation directly. It reduces a slice’s capacity to its length without changing its elements or length. The detail that matters is what this does, and doesn’t, imply about memory.

Go 10 Sep 2026 7 min read

Replace Slice Ranges in Go with slices.Replace

Replacing part of a Go slice sounds simple until the replacement has a different length from the range it replaces. A two-element range might become one element, four elements, or nothing at all. At that point, a few append calls can work, but they make the indexing and storage behavior harder to read than the operation itself. slices.Replace handles that splice-like operation directly. Give it a slice, a half-open range, and the replacement values; it returns the resulting slice. The function can shrink, preserve, or grow the length depending on how many values you provide.

Go 10 Sep 2026 5 min read

Repeat Slice Patterns in Go with slices.Repeat

Repeating a short slice pattern is simple enough to write by hand, but the bookkeeping gets noisy: calculate the final size, allocate storage, then append or copy the pattern the right number of times. Since Go 1.23, slices.Repeat handles that operation directly. The function is useful when the thing you want to repeat is already a slice: a test fixture pattern, a protocol marker, a sequence of defaults, or any other small block of values. It returns a new slice rather than extending or rearranging the input.

Go 10 Sep 2026 5 min read

Remove Consecutive Duplicates in Go with slices.Compact

If a Go slice contains repeated values next to each other, you don’t need to write an index-heavy loop to collapse them. Since Go 1.21, slices.Compact handles that operation directly for comparable element types. The word consecutive matters. Given []string{"api", "api", "web", "api"}, the result is []string{"api", "web", "api"}. The last "api" stays because it belongs to a different run. slices.Compact isn’t a general-purpose “unique values” function. What slices.Compact actually does slices.Compact replaces each consecutive run of equal elements with its first element. It modifies the slice’s backing array and returns a slice with the resulting length.

Go 10 Sep 2026 6 min read

Process Go Slices in Batches with slices.Chunk

Batching a slice sounds simple until the loop starts collecting edge cases: the final batch may be short, an empty input needs sensible behavior, and careless subslicing can leave each batch with capacity to overwrite later elements. Go 1.23 added slices.Chunk, which handles that bookkeeping and exposes the batches as an iterator. If you already have the data in a slice and want to process consecutive groups without first building a [][]T, it’s a useful small tool.

Go 10 Sep 2026 7 min read

Preallocate Append Capacity in Go with slices.Grow

Sometimes you know a slice is about to receive several elements, even though you don’t have those elements yet. Repeated append calls will grow the slice automatically, but some of those appends may have to allocate a larger backing array and copy the existing elements. slices.Grow lets you reserve enough capacity for a known amount of upcoming growth. It doesn’t add placeholder elements and it doesn’t change the slice’s length. It simply returns a slice that has room for at least the requested number of additional elements.

Go 10 Sep 2026 5 min read

Iterate Go Slices in Reverse with slices.Backward

Walking a slice from the end used to mean writing the index loop yourself. That works, but the loop mechanics can distract from the actual job, especially when you need both the original index and the value. Since Go 1.23, slices.Backward provides that traversal directly. It returns an iterator. The slice stays in its original order, no reversed copy is created, and the indexes you receive are the real indexes from the source slice.

Go 10 Sep 2026 5 min read

Find Values and Insertion Points with slices.BinarySearch

When a Go slice is already sorted, scanning it from the beginning to find one value throws away useful information. slices.BinarySearch uses that ordering directly. It returns both an index and a found flag, and the index remains useful even when the target isn’t present. That second behavior is easy to overlook. slices.BinarySearch isn’t only a membership check; it also tells you where a missing value belongs if you want to preserve the slice’s sort order.

Go 10 Sep 2026 4 min read

Find the First Matching Slice Element in Go with slices.IndexFunc

Searching a slice is easy when the element itself is comparable and you already know the exact value. Real programs often need something slightly different: the first queued job, the first expired token, or the first record whose normalized name matches some input. slices.IndexFunc handles that case directly. You provide a predicate, and it returns the index of the first element for which that predicate is true. If nothing matches, it returns -1.

Go 10 Sep 2026 6 min read

Filter Go Slices in Place with slices.DeleteFunc

Filtering a slice often starts with a small loop: inspect each element, keep the ones you want, and return the shorter result. When changing the original backing array is acceptable, slices.DeleteFunc gives that operation a standard-library name and avoids a hand-written compaction loop. The useful detail is in “changing the original backing array.” slices.DeleteFunc isn’t a general-purpose immutable filter. It removes matching elements in place and returns the shortened slice, so it works best when the caller owns the input and no longer needs its old contents.

Go 10 Sep 2026 7 min read

Compare Go Slices with Custom Equality Using slices.EqualFunc

Two slices can represent the same information without being directly comparable element by element. One side might contain structs while the other contains strings. Text may need case-insensitive comparison. IDs may arrive in different concrete types even though your application treats them as the same value. When equality depends on a rule rather than Go’s == operator, slices.EqualFunc puts that rule in one place and handles the slice traversal for you.

Go 10 Sep 2026 6 min read

Compare Go Slices Lexicographically with slices.Compare

Sometimes equality isn’t enough. You may need to order version components, compare path segments, choose which byte sequence comes first, or sort records by a slice-valued key. Writing that comparison by hand is straightforward, but the prefix case and the meaning of the return value are easy places to introduce small bugs. For slices whose element type is ordered, slices.Compare provides the standard lexicographic comparison directly. It compares elements from left to right and, when all shared elements match, treats the shorter slice as smaller.

Go 10 Sep 2026 5 min read

Combine Go Slices with slices.Concat

Combining several slices often starts as a tiny append expression and ends with an ownership question: did the result reuse one of the input backing arrays, and can a later append or mutation affect data another part of the program still uses? Since Go 1.22, slices.Concat gives this operation a direct standard-library form. It combines multiple slices into a new slice, which is especially useful when the result should be treated as its own collection rather than as an extension of one input.

Go 10 Sep 2026 6 min read

Check Slice Predicates in Go with slices.ContainsFunc

Sometimes you don’t need the matching element or its position. You only need to answer a yes-or-no question: does this slice contain anything that satisfies a condition? For that case, slices.ContainsFunc is more direct than writing an index loop or calling slices.IndexFunc and comparing its result with -1. It accepts a predicate, checks elements in order, and returns as soon as one matches. What slices.ContainsFunc does The function accepts any slice element type because the predicate decides what counts as a match:

Go 10 Sep 2026 6 min read

Append Iterator Values to Go Slices with slices.AppendSeq

An iterator is convenient while data is flowing through a pipeline, but sooner or later you may need those values in a slice. If you already have a destination slice, collecting the iterator separately and then appending it creates an unnecessary intermediate step. Go 1.23 added slices.AppendSeq for exactly this boundary. It consumes an iter.Seq, appends each yielded value to an existing slice, and returns the resulting slice. What slices.AppendSeq does The function has a compact signature: