snippetgoMajor
How to check if a slice has a given index in Go?
Viewed 0 times
indexhashowslicecheckgiven
Problem
We can easily do that with maps:
But not with slices:
Surprised this wasn't asked before. Maybe I'm on the wrong mental model with Go slices?
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?
Solution
There is no sparse slices in Go, so you could simply check the length:
If the length is greater than 3, you know that the index 3 and all those before that exist.
if len(mySlice) > 3 {
// ...
}If the length is greater than 3, you know that the index 3 and all those before that exist.
Code Snippets
if len(mySlice) > 3 {
// ...
}Context
Stack Overflow Q#27252152, score: 90
Revisions (0)
No revisions yet.