Contains Index And Equal Check Slices

Probe slices with Contains, Index, and Equal: presence checks compare by ==, Index returns the first match or -1, and Equal treats nil as empty.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	features := []string{"auth", "billing", "search"}

	// slices.Contains: a presence check that compares with ==
	fmt.Println("has billing:", slices.Contains(features, "billing"))
	fmt.Println("has audit:", slices.Contains(features, "audit"))

	// slices.Index: the first matching index, or -1 when nothing matches
	fmt.Println("index of search:", slices.Index(features, "search"))
	fmt.Println("index of audit:", slices.Index(features, "audit"))

	// slices.Equal: true only when lengths and every element match
	a := []int{1, 2, 3}
	b := []int{1, 2, 3}
	c := []int{1, 2, 4}
	fmt.Println("a==b:", slices.Equal(a, b), "a==c:", slices.Equal(a, c))

	// A nil slice and an empty slice both have length 0: Equal treats them as equal
	var nilSlice []int
	fmt.Println("nil==empty:", slices.Equal(nilSlice, []int{}))
}

Inside the snippet

Structurally, expect the function main and nothing else.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func main()

Look for the has billing:, has audit:, index of search: prefixes when the file runs; they tie each line to its step.

Core lines

features := []string{"auth", "billing", "search"}

Interactive Tools for This Topic

FAQ

What does Contains Index And Equal Check Slices print when run?
Execute the whole file; each printed line is prefixed with a label like `has billing:`, `has audit:`, `index of search:`.