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.

GoData Integrity

Code

gosnippet
41 lines
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

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:`.