From: Matthew Dempsky Date: Sun, 6 Jan 2013 22:59:37 +0000 (+1100) Subject: bytes: Examples recommending bytes.Compare(a, b) rel_op 0 to test a rel_op b. X-Git-Tag: go1.1rc2~1472 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=56961274bbbdac59ab23af9ad592dfac89c94869;p=gostls13.git bytes: Examples recommending bytes.Compare(a, b) rel_op 0 to test a rel_op b. R=golang-dev, minux.ma, rsc, adg CC=golang-dev https://golang.org/cl/7042045 --- diff --git a/src/pkg/bytes/example_test.go b/src/pkg/bytes/example_test.go index 1774a5ab42..5f7e18c9f6 100644 --- a/src/pkg/bytes/example_test.go +++ b/src/pkg/bytes/example_test.go @@ -10,6 +10,7 @@ import ( "fmt" "io" "os" + "sort" ) func ExampleBuffer() { @@ -27,3 +28,41 @@ func ExampleBuffer_reader() { io.Copy(os.Stdout, dec) // Output: Gophers rule! } + +func ExampleCompare() { + // Interpret Compare's result by comparing it to zero. + var a, b []byte + if bytes.Compare(a, b) < 0 { + // a less b + } + if bytes.Compare(a, b) <= 0 { + // a less or equal b + } + if bytes.Compare(a, b) > 0 { + // a greater b + } + if bytes.Compare(a, b) >= 0 { + // a greater or equal b + } + + // Prefer Equal to Compare for equality comparisons. + if bytes.Equal(a, b) { + // a equal b + } + if !bytes.Equal(a, b) { + // a not equal b + } +} + +func ExampleCompare_search() { + // Binary search to find a matching byte slice. + var needle []byte + var haystack [][]byte // Assume sorted + i := sort.Search(len(haystack), func(i int) bool { + // Return needle <= haystack[i]. + return bytes.Compare(needle, haystack[i]) <= 0 + }) + if i < len(haystack) && bytes.Equal(needle, haystack[i]) { + // Found it! + } +}