
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Slice Contains an Element in Golang
Many languages do provide a method similar to indexOf() where one can find the existence of a particular element in an array-like data structure. However, in Golang, there's no such method and we can simply implement it with the help of a for-range loop.
Let's suppose we have a slice of strings, and we want to find out whether a particular string exists in the slice or not.
Example 1
Consider the code shown below.
package main import ( "fmt" ) func Contains(sl []string, name string) bool { for _, value := range sl { if value == name { return true } } return false } func main() { sl := []string{"India", "Japan", "USA", "France"} countryToCheck := "Argentina" isPresent := Contains(sl, countryToCheck) if isPresent { fmt.Println(countryToCheck, "is present in the slice named sl.") } else { fmt.Println(countryToCheck, "is not present in the slice named sl.") } }
In the above code, we are trying to find if the string with the value " Argentina" is present in the slice "sl" or not.
Output
If we run the command go run main.go, then we will get the following output in the terminal.
Argentina is not present in the slice named sl.
We can also print the index at which we have encountered an element in a slice.
Example 2
Consider the code shown below.
package main import ( "fmt" ) func Contains(sl []string, name string) int { for idx, v := range sl { if v == name { return idx } } return -1 } func main() { sl := []string{"India", "Japan", "USA", "France"} countryToCheck := "USA" index := Contains(sl, countryToCheck) if index != -1 { fmt.Println(countryToCheck, "is present in the slice named sl at index", index) } else { fmt.Println(countryToCheck, "is not present in the slice named sl.") } }
Output
If we run the command go run main.go then we will get the following output in the terminal.
USA is present in the slice named sl at index 2