Commit 56961274 authored by Matthew Dempsky's avatar Matthew Dempsky Committed by Andrew Gerrand

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
parent 396c957a
......@@ -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!
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment