]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: Examples recommending bytes.Compare(a, b) rel_op 0 to test a rel_op b.
authorMatthew Dempsky <mdempsky@google.com>
Sun, 6 Jan 2013 22:59:37 +0000 (09:59 +1100)
committerAndrew Gerrand <adg@golang.org>
Sun, 6 Jan 2013 22:59:37 +0000 (09:59 +1100)
R=golang-dev, minux.ma, rsc, adg
CC=golang-dev
https://golang.org/cl/7042045

src/pkg/bytes/example_test.go

index 1774a5ab42612a563b702f696e06d3c7d9fbd686..5f7e18c9f64c518ae9730812cf657f989a2ea910 100644 (file)
@@ -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!
+       }
+}