Based on this fairly simple code based on the sort package. The response index of o1
is invalid as pointed by @JimB because a bigger or equals operator is required for binary search
l := []string{"o1", "o2", "o3"}
i1 := sort.Search(len(l), func(i int) bool { return strings.EqualFold(l[i], "o1") })
fmt.Println("o1:", i1) //PRINTS 3 - WRONG
https://play.golang.org/p/nUs-ozTYsY
The working solution is:
l := []string{"o1", "o2", "o3"}
i1 := sort.Search(len(l), func(i int) bool { return l[i] >= "o1" })
fmt.Println("o1:", i1)
https://play.golang.org/p/WRsijy_xzV
However this still it's important to bare in mind a important last check. The return value is the index to insert x
, which means that you can end up with something like:
o1: 0 (index 0)
o2: 1
o3: 2
o777: 0 (Same 0 index!)
Therefore it's important as pointed by @JimB to check for data[i] == 23
separately.
if i < len(data) && ---> data[i] == x <--- {
x is present at data[i]
} else {
...
}