sort.Search <https://pkg.go.dev/sort#Search> is a binary chop, and needs an ordering condition, >= or <=. If you use == then it cannot work.
In addition you're getting a panic here: if ret < len(haystack) { index += ret log.Println("found", index, haystack[index]) } by letting index increment past the end of the slice. On Tuesday, 11 October 2022 at 13:22:29 UTC+1 ljh wrote: > Hi community, > > I used sort.Search on a sorted slice in below code started at Line 36, and > it worked. > > I also tried to call sort.Search in a loop, started at Line 53. It does > not seem to work. How can I correct the loop version? > > Thanks > > --- > > package main > > import ( > "log" > "sort" > ) > > type T struct { > name string > } > > func main() { > log.SetFlags(log.LstdFlags | log.Llongfile) > > haystack := []T{ > // {name: "apple", }, > {name: "compote", }, //dup > {name: "orange", }, > {name: "compote", }, //dup > } > > sort.Slice(haystack, func(i, j int) bool { > if haystack[i].name < haystack[j].name { > return true > } else { > return false > } > }) > > for _, t := range haystack { > log.Println("sorted", t) > } > > needle := T{name: "compote"} > > // Style 1: ok, lower upper bounds style // Line 36 > /* > lower := sort.Search(len(haystack), func(i int) bool { > return haystack[i].name == needle.name > }) > > upper := sort.Search(len(haystack), func(i int) bool { > return haystack[i].name > needle.name > }) > > if lower != len(haystack) { > for i := lower; i != upper; i++ { > log.Println("found", i, haystack[i]) > } > } > */ > > // Style 2: error, loop style // Line 53 > for index := 0; index < len(haystack); index++ { > ret := sort.Search(len(haystack[index:]), func(i int) bool { > return haystack[index:][i].name == needle.name }) > > log.Println(index, ret) > > if ret < len(haystack) { > index += ret > log.Println("found", index, haystack[index]) > } > } > } > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/efc0960f-85f7-45b4-8099-a743665592bcn%40googlegroups.com.