如何检查切片在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?

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.

https://github.com/chenhg5/collection is a package which can help you. like this:

a := []interface{}{"1","2","3","4"}

fmt.Println(Collect(a).Contains("3"))

// Output: true