From 56961274bbbdac59ab23af9ad592dfac89c94869 Mon Sep 17 00:00:00 2001 From: Matthew Dempsky Date: Mon, 7 Jan 2013 09:59:37 +1100 Subject: [PATCH] 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 --- src/pkg/bytes/example_test.go | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) 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! + } +} -- 2.48.1