Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a slice has a given index in Go?

Tags:

slice

go

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?

like image 627
marcio Avatar asked Dec 02 '14 14:12

marcio


People also ask

How do you check if a slice contains an element in Go?

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.

How do you check if a slice contains a string Golang?

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.

How do I find my slice element?

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.


1 Answers

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.

like image 170
laurent Avatar answered Sep 30 '22 03:09

laurent