snippetgoMajor
How to find out element position in slice?
Viewed 0 times
howslicefindelementpositionout
Problem
How does one determine the position of an element present in slice?
I need something like the following:
I need something like the following:
type intSlice []int
func (slice intSlice) pos(value int) int {
for p, v := range slice {
if (v == value) {
return p
}
}
return -1
}Solution
Sorry, there's no generic library function to do this. Go doesn't have a straight forward way of writing a function that can operate on any slice.
Your function works, although it would be a little better if you wrote it using
If you happen to have a byte slice, there is bytes.IndexByte.
Your function works, although it would be a little better if you wrote it using
range.If you happen to have a byte slice, there is bytes.IndexByte.
Context
Stack Overflow Q#8307478, score: 86
Revisions (0)
No revisions yet.