Slices Contains IndexFunc EqualFunc

Test membership and equality with slices.Contains, ContainsFunc, IndexFunc, and EqualFunc so lookups and comparisons stay declarative.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"slices"
	"strings"
)

func main() {
	firewall := []string{"web", "api", "jobs"}

	// Contains:精确成员判断
	fmt.Println("has api:", slices.Contains(firewall, "api"))
	fmt.Println("has db :", slices.Contains(firewall, "db"))

	// ContainsFunc:谓词成员判断,例如按前缀
	fmt.Println("has 'ap' prefix:", slices.ContainsFunc(firewall, func(s string) bool {
		return strings.HasPrefix(s, "ap")
	}))

	// IndexFunc:返回第一个命中下标,未命中返回 -1
	fmt.Println("first 3-char at:", slices.IndexFunc(firewall, func(s string) bool {
		return len(s) == 3
	}))

	// EqualFunc:逐项用自定义比较判断两序列等价
	a := []string{"Web", "API"}
	b := []string{"web", "api"}
	fmt.Println("equal ignoring case:", slices.EqualFunc(a, b, strings.EqualFold))
}

How it works

Count the function main as the entire surface area of Slices Contains IndexFunc EqualFunc.

Applying it

The demo output is labeled (has api:, has db :, has 'ap' prefix:), so every line in the printed output names the step that produced it.

Statements that matter

return strings.HasPrefix(s, "ap")
return len(s) == 3

Interactive Tools for This Topic

FAQ

What does Slices Contains IndexFunc EqualFunc print when run?
Running the file directly is enough — expect labeled output lines such as `has api:`, `has db :`, `has 'ap' prefix:`.