package slices
import "k8s.io/utils/strings/slices"
Package slices defines various functions useful with slices of string type.
The goal is to be as close as possible to
https://github.com/golang/go/issues/45955. Ideal would be if we can just
replace "stringslices" if the "slices" package becomes standard.
Code:
Output: Code:
Output:Example¶
{
a := []string{
"10.0.0.0", "FOO", "1000::1", "fd80::4%eth0", "BAR", "192.168.1.300",
"172.12.0.1", "fc00::5000",
}
v := func(s string) bool { return net.ParseIP(s) == nil }
if notIP := Filter(nil, a, v); len(notIP) > 0 {
fmt.Println("Invalid", notIP)
}
fmt.Println(Filter(nil, a, utilnet.IsIPv6String))
// Output:
// Invalid [FOO fd80::4%eth0 BAR 192.168.1.300]
// [1000::1 fc00::5000]
}
Invalid [FOO fd80::4%eth0 BAR 192.168.1.300]
[1000::1 fc00::5000]
Example (Regexp)¶
{
a := []string{
"10.0.0.0", "FOO", "1000::1", "fd80::4%eth0", "BAR", "192.168.1.300",
"172.12.0.1", "fc00::5000",
}
re := regexp.MustCompile("^[A-Z]+$")
fmt.Println(Filter(nil, a, re.MatchString))
// Output: [FOO BAR]
}
[FOO BAR]
Index ¶
Examples ¶
Variables ¶
Clone returns a new clone of s.
Deprecated: use stdlib slices.Clone instead.
Contains reports whether v is present in s.
Deprecated: use stdlib slices.Contains instead.
Equal reports whether two slices are equal: the same length and all elements equal. If the lengths are different, Equal returns false. Otherwise, the elements are compared in index order, and the comparison stops at the first unequal pair.
Deprecated: use stdlib slices.Equal instead.
Index returns the index of the first occurrence of v in s, or -1 if not present.
Deprecated: use stdlib slices.Index instead.
Functions ¶
func Filter ¶
Filter appends to d each element e of s for which keep(e) returns true. It returns the modified d. d may be s[:0], in which case the kept elements will be stored in the same slice. if the slices overlap in some other way, the results are unspecified. To create a new slice with the filtered results, pass nil for d.
Deprecated: use stdlib slices.DeleteFunc instead.
Code:
Output:Example (Empty)¶
{
s := []string{"FOO", "", "", "BAR", "fd80::8888", ""}
fmt.Println(Filter(nil, s, func(s string) bool { return s != "" }))
// Output: [FOO BAR fd80::8888]
}
[FOO BAR fd80::8888]
Source Files ¶
slices.go
- Version
- v0.0.0-20260319190234-28399d86e0b5 (latest)
- Published
- Mar 19, 2026
- Platform
- linux/amd64
- Imports
- 1 packages
- Last checked
- 9 hours ago –
Tools for package owners.