Splitting Strings in Go Without an Extra Slice While Keeping Separators: strings.SplitAfterSeqBrief · digest for November 30
Brief≈ 1 min

Splitting Strings in Go Without an Extra Slice While Keeping Separators: strings.SplitAfterSeq

When you split a long string with strings.SplitAfter, Go allocates memory for the entire []string slice upfront. For a single loop pass that's wasted work, and if you break out on the second item it's even worse.

Go 1.24 added a lazy alternative to the strings package: strings.SplitAfterSeq. It yields substrings one at a time via an iter.Seq[string] iterator directly inside for range without allocating a slice. Each fragment keeps the trailing separator, just like SplitAfter. If you don't want the separators, strings.SplitSeq sits right next to it.

// Keep the separator at the end of each part
for part := range strings.SplitAfterSeq("a,b,c", ",") {
    fmt.Println(part)
}
// Output: "a,", "b,", "c"

// Same split, without separators
for part := range strings.SplitSeq("a,b,c", ",") {
    fmt.Println(part)
}
// Output: "a", "b", "c"

Both functions return a single-use iterator: you can't save it and loop over it twice—the second loop yields nothing, so you have to call the function again. Edge cases match SplitAfter: an empty separator splits after every UTF-8 rune, and if both arguments are empty, the loop runs zero times.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 5