slices

package
v2.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 28, 2023 License: MIT Imports: 0 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[E comparable](s []E, e ...E) bool

All If all the elements in e that are in the s then return true

Example
fmt.Println(All([]string{"AA", "B", "C"}, "C"))
fmt.Println(All([]string{"AA", "B", "C"}, "AA", "C"))
fmt.Println(All([]string{"AA", "B", "C"}, "AK", "C"))
fmt.Println(All([]string{"AA", "B", "C"}, []string{"B", "C"}...))
fmt.Println(All([]int{1, 3, 5}, 3))
fmt.Println(All([]int{1, 3, 5}, 2, 3))
fmt.Println(All([]int{1, 3, 5}, 1, 5))

// slice為空必定為false
fmt.Println(All([]int{}, 0))

// 此外檢驗空資料是否於某slice也視為false
fmt.Println(All([]int{}, []int{}...))
Output:

true
true
false
true
true
false
true
false
false

func Any

func Any[E comparable](s []E, e ...E) bool

Any If one of the elements in e that are in the s then return true

Example
fmt.Println(Any([]string{"AA", "B", "C"}, "AA", "C"))
fmt.Println(Any([]string{"AA", "B", "C"}, "AK", "C"))
fmt.Println(Any([]string{"AA", "B", "C"}, []string{"Z", "D"}...))
fmt.Println(Any([]int{1, 2, 3}, []int{2, 8, 9}...))
fmt.Println(Any([]int{1, 2, 3}, 5, 7, 9))
fmt.Println(Any([]int{1, 2, 3}, 3))
Output:

true
true
false
true
false
true

func ChunkBy added in v2.3.0

func ChunkBy[T any](items []T, size int) (chunks [][]T)

ChunkBy slice分組

Example
src := []int{1, 2, 3, 4, 5}
fmt.Println(ChunkBy(src, 5))
fmt.Println(ChunkBy(src, 2))
fmt.Println(ChunkBy(src, 1))
fmt.Println(ChunkBy([]string{"a", "b", "c"}, 2))
Output:

[[1 2 3 4 5]]
[[1 2] [3 4] [5]]
[[1] [2] [3] [4] [5]]
[[a b] [c]]
Example (Panic)
defer func() {
	err := recover()
	if err == nil {
		panic("should panic")
	}
	fmt.Printf("error: %s\n", err)
}()
ChunkBy([]int{1, 2, 3, 4, 5}, 0)
Output:

error: The size must be greater than zero

func Contains

func Contains[E comparable](s []E, e E) bool

Contains reports whether e is present in s

Example
fmt.Println(Contains([]string{"A", "B", "C"}, "B"))
fmt.Println(Contains([]string{"A", "B", "C"}, "Z"))
fmt.Println(Contains([]int{1, 3, 5, 7}, 5))
fmt.Println(Contains([]int{1, 3, 5, 7}, 9))
fmt.Println(Contains([]int{}, 0))
Output:

true
false
true
false
false

func Index

func Index[E comparable](s []E, e E) int

Index returns the index of the first occurrence of e in s, or -1 if not present.

Example
fmt.Println(Index([]string{"A", "B", "C"}, "B"))
fmt.Println(Index([]int{1, 3, 5, 7}, 7))

// slice為空,必定回傳-1
fmt.Println(Index([]int{}, 0))
Output:

1
3
-1

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL