Slice Contains Method in Go

In Go 1.18 version, Golang team introduced a new experimental package slices which uses generics.

And this slices package contains a collection of generic functions that operate on slices of any element type.

And it has slices.Contains() method Which checks if an element exist in slice or not.

Use the below command to get slices package.

go get golang.org/x/exp/slices

Go Slice Contains Method example

Let’s go through an example to understand if further.

Import the slices package and use slices.Contains() method as shown below.

package main

import (
	"fmt"

	"golang.org/x/exp/slices"
)

func main() {
	fmt.Println("Go Slice Contains Method example")
	fruits := []string{"apple", "orange", "banana"}
	fmt.Println(slices.Contains(fruits, "banana")) // true
}

//OUTPUT:

Go Slice Contains Method example
true

Follow us @ twitter, facebook and linkedin For latest news and articles about Go Language

☝ ✍ Go Language Tutorial ✍☝
Get a short & sweet Go Language tutorials delivered to your inbox every couple of days. No spam ever. Unsubscribe any time.
Avatar

Arunkumar Gudelli

I am One among a million Software engineers of India. I write beautiful markup.I make the Web useful.