Partition Slices Into Two Stable Groups
Split one slice into info and warn groups with two append targets, preserving original order in each group without mutating the source.
Code
package main
import "fmt"
type Event struct {
Name string
Level string // "info" or "warn"
}
// stable partition: two groups keep source order, source slice untouched.
func partition(events []Event) (infos, warns []Event) {
for _, ev := range events {
if ev.Level == "warn" {
warns = append(warns, ev)
continue
}
infos = append(infos, ev)
}
return infos, warns
}
func main() {
events := []Event{
{"boot", "info"},
{"disk-full", "warn"},
{"ready", "info"},
{"retry", "warn"},
}
infos, warns := partition(events)
fmt.Println("order preserved:")
for _, ev := range infos {
fmt.Println(" info:", ev.Name)
}
for _, ev := range warns {
fmt.Println(" warn:", ev.Name)
}
// the source slice still holds all four events
fmt.Println("source still has", len(events), "events")
}How the pieces connect — Partition Slices Into Two Stable Groups
Partition Slices Into Two Stable Groups reduces to the functions partition and main.
The file repeats itself only inside for _, ev := range events.
Caveats
- Stands alone as a file: any imports it has come straight from the runtime itself.
Using it
Signature: func partition(events []Event) (infos, warns []Event)
The run prints order preserved:, info:, warn: — each prefix names the step that produced it.
The entry point wires partition together — run it once and the whole demo flows.
Key statements
func partition(events []Event) (infos, warns []Event) {
for _, ev := range events {
if ev.Level == "warn" {
warns = append(warns, ev)
continue
}
infos = append(infos, ev)
}
return infos, warns
}
for _, ev := range infos {
fmt.Println(" info:", ev.Name)
}
for _, ev := range warns {
fmt.Println(" warn:", ev.Name)
}
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 Partition Slices Into Two Stable Groups print when run?
- Run it as a complete program — the output lines carry labels such as `order preserved:`, `info:`, `warn:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.