Skip to content

Instantly share code, notes, and snippets.

@genghisjahn
Last active April 12, 2016 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genghisjahn/2c7ad47c5d148805f5d4378f029b4bd8 to your computer and use it in GitHub Desktop.
Save genghisjahn/2c7ad47c5d148805f5d4378f029b4bd8 to your computer and use it in GitHub Desktop.
Golang Search Contains
//https://golang.org/src/sort/search.go
//https://golang.org/pkg/sort/#Search
package main
import (
"fmt"
"sort"
)
type Thing struct {
This string
That int
}
type Things []Thing
func (slice Things) Len() int {
return len(slice)
}
func (slice Things) Less(i, j int) bool {
return slice[i].This < slice[j].This
}
func (slice Things) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
func main() {
target := Thing{"Bill", 34}
t := Things{Thing{"Jon", 42}, Thing{"Charles", 41}, Thing{"Bill", 34}, Thing{"David", 44}}
sort.Sort(t)
i := sort.Search(len(t),
func(i int) bool { return t[i].This >= target.This && t[i].That >= target.That })
if i < len(t) && t[i] == target {
fmt.Printf("found \"%v\" at t[%d]\n", t[i], i)
}
}
@genghisjahn
Copy link
Author

Show how to implement with an interface for multiple types (perhaps using a hash)

Show how to use using Go Generate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment