strings.SplitSeq Splits Without Allocating
Iterate delimiters with strings.SplitSeq to stream substrings without materializing a slice, and keep strings.Split for indexed access.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.