Skip to content

Archive

Go

100 articles
Go 11 Sep 2026 5 min read

Iterate Go Map Keys with maps.Keys

Sometimes you need only the keys from a Go map. A plain range loop handles that case well, but an iterator becomes useful when the keys need to flow into another iterator-aware API or when a function should expose keys without first allocating a slice. Since Go 1.23, maps.Keys returns an iter.Seq over a map’s keys. You can range over it directly, stop early, or pass it to helpers such as slices.Sorted and slices.Collect.

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 4 min read

Copy Entries Between Go Maps with maps.Copy

Sometimes you already have a destination map and need to add another map’s entries without writing a loop. Go’s maps.Copy does exactly that: it copies every key-value pair from a source map into an existing destination map. The operation is deliberately simple. Existing destination entries remain when their keys aren’t present in the source. When both maps contain the same key, the source value replaces the destination value. That makes maps.Copy useful for applying defaults, overrides, accumulated state, and other map-to-map merges where replacement is the intended conflict rule.

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.

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 6 min read

Compare Go Maps with Custom Value Rules Using maps.EqualFunc

Two maps can represent the same application state even when their values aren’t directly comparable with ==. One map might hold structs containing slices, another might use a different value type, or a text field might be considered equal regardless of letter case. maps.EqualFunc handles that situation by keeping key comparison fixed while letting you define value equality. It is a compact option when the question is strictly whether two maps contain the same keys and equivalent values.

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 7 min read

Test Concurrent Go Code with testing/synctest

Tests for concurrent Go code often become timing tests by accident. A goroutine starts, the test sleeps for 20 milliseconds, then checks whether something happened. That can pass thousands of times and still fail on a loaded CI runner because the sleep never proved the goroutine reached the state you cared about. Go’s testing/synctest package gives these tests a better model. It runs code inside an isolated bubble where time is virtualized, and synctest.Wait can synchronize the test with goroutines in that bubble. The result is especially useful for code built around timers, context deadlines, retries, and background goroutines.

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.