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 ¶
- func Clone(s []string) []string
- func Contains(s []string, v string) bool
- func Equal(s1, s2 []string) bool
- func Filter(d, s []string, keep func(string) bool) []string
- func Index(s []string, v string) int
Examples ¶
Functions ¶
func Clone ¶
Clone returns a new clone of s.
func Contains ¶
Contains reports whether v is present in s.
func Equal ¶
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.
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.
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]
func Index ¶
Index returns the index of the first occurrence of v in s, or -1 if not present.
Source Files ¶
slices.go
- Version
- v0.0.0-20250321185631-1f6e0b77f77e (latest)
- Published
- Mar 21, 2025
- Platform
- linux/amd64
- Last checked
- 1 month ago –
Tools for package owners.