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

GoSlice

Go Problem Overview


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?

Go Solutions


Solution 1 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcioView Question on Stackoverflow
Solution 1 - GolaurentView Answer on Stackoverflow