Generic Map And Filter Slice Helpers

Write Map and Filter once with generics, reuse them for any element type, and chain filter before map while types infer at the call site.

GoData Integrity

Code

gosnippet
39 lines
package main

import "fmt"

// 泛型助手:一次编写,任意元素类型复用
func Map[T, U any](src []T, fn func(T) U) []U {
	out := make([]U, 0, len(src))
	for _, v := range src {
		out = append(out, fn(v))
	}
	return out
}

func Filter[T any](src []T, keep func(T) bool) []T {
	out := make([]T, 0, len(src))
	for _, v := range src {
		if keep(v) {
			out = append(out, v)
		}
	}
	return out
}

func main() {
	ports := []int{80, 443, 8080, 22}

	urls := Map(ports, func(p int) string {
		return fmt.Sprintf(":%d", p)
	})
	fmt.Println("mapped:", urls)

	web := Filter(ports, func(p int) bool { return p >= 80 })
	fmt.Println("filtered:", web)

	// 链式组合:先过滤再映射
	labels := Map(Filter(ports, func(p int) bool { return p != 22 }),
		func(p int) string { return fmt.Sprint(p) })
	fmt.Println("labels:", labels)
}

A guided pass over the statements

Generic Map And Filter Slice Helpers is built around the function main.

Iteration happens inside for _, v := range src — everything outside it runs once.

Using it

The demo output is labeled (mapped:, filtered:, labels:), so each line traces straight back to the statement that printed it.

Key statements

func Map[T, U any](src []T, fn func(T) U) []U {
	out := make([]U, 0, len(src))
	for _, v := range src {
		out = append(out, fn(v))
	}
	return out
}
return fmt.Sprintf(":%d", p)
labels := Map(Filter(ports, func(p int) bool { return p != 22 }),
	func(p int) string { return fmt.Sprint(p) })

Interactive Tools for This Topic

FAQ

What does Generic Map And Filter Slice Helpers print when run?
Running the file directly is enough — expect labeled output lines such as `mapped:`, `filtered:`, `labels:`.