We can easily do that with maps:
item, ok := myMap["index"]
But not with slices:
item, ok := mySlice[3] // panic!
Surprised this wasn't asked before. Maybe I'm on the wrong mental model with Go slices?
How to check if a slice contains an element. To check if a particular element is present in a slice object, we need to perform the following steps: Use a for loop to iterate over each element in the slice . Use the equality operator ( == ) to check if the current element matches the element you want to find.
To do this, you need to write your own contains() function that takes two arguments: the slice and the element to find. As a result, it should return true if the slice contains this element and false otherwise.
In the Go slice, you can search an element of string type in the given slice of strings with the help of SearchStrings() function. This function searches for the given element in a sorted slice of strings and returns the index of that element if present in the given slice.
There is no sparse slices in Go, so you could simply check the length:
if len(mySlice) > 3 { // ... }
If the length is greater than 3, you know that the index 3 and all those before that exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With