strings.SplitSeq Splits Without Allocating

Iterate delimiters with strings.SplitSeq to stream substrings without materializing a slice, and keep strings.Split for indexed access.

GoData Integrity

Code

gosnippet
22 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	record := "us-east,eu-west,ap-south,sa-east"

	// SplitSeq 按需产出子串:不预先物化整个切片(Go 1.24+)
	count := 0
	for region := range strings.SplitSeq(record, ",") {
		fmt.Println("region:", region)
		count++
	}
	fmt.Println("counted:", count)

	// 对照 strings.Split:一次性分配切片,适合需要索引或长度的场景
	parts := strings.Split(record, ",")
	fmt.Println("split len:", len(parts), "second:", parts[1])
}

What happens, in what order

strings.SplitSeq Splits Without Allocating is built around the function main.

Iteration happens inside for region := range strings.SplitSeq(record, ",") — everything outside it runs once.

Applying it

Running the file prints labeled results such as region:, counted:, split len: — each operation’s effect is visible in the output.

Statements that matter

for region := range strings.SplitSeq(record, ",") {
fmt.Println("region:", region)
count++
}

Interactive Tools for This Topic

FAQ

What does strings.SplitSeq Splits Without Allocating print when run?
Invoke the file as-is — the `region:`, `counted:`, `split len:` prefixes identify which step printed each line.