Ad space (banner)
๐ŸนGo Lessons
Lesson 22 / 68

Searching a Slice

In this lesson you will learn the basic way to search within a slice in Go so you can check whether a value is present. This is for anyone searching for "Go slice search how to".

Go has no simple built-in "does it contain this" function, so the basic approach is to loop with for and compare items one at a time.

The sample code examines the slice item by item with for _, f := range fruits and sets found to true when the condition f == "orange" holds. Go 1.21 and later also added the handy slices.Contains to the standard library, which is shorter still.

A common stumbling block for beginners is performance with larger data sets. Comparing one at a time in a for loop is easy to read, but a map-based lookup is faster once there is a lot of data, so pick to suit the job.

In real-world development this search comes up whenever you need to confirm that a list contains a particular product ID or user name.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)