Last active
April 12, 2016 14:55
-
-
Save genghisjahn/2c7ad47c5d148805f5d4378f029b4bd8 to your computer and use it in GitHub Desktop.
Golang Search Contains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Show how to implement with an interface for multiple types (perhaps using a hash)
Show how to use using Go Generate