Slices Contains IndexFunc EqualFunc
Test membership and equality with slices.Contains, ContainsFunc, IndexFunc, and EqualFunc so lookups and comparisons stay declarative.
Code
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
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 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.