Contains, Index, HasPrefix
bytes.Contains([]byte("gopher"), []byte("ph")) // true
bytes.Index([]byte("gopher"), []byte("ph")) // 2
bytes.HasPrefix([]byte("gopher"), []byte("go")) // true
bytesThe strings package, but for []byte. Plus Buffer (a mutable growable byte buffer) and NewReader.
Most functions mirror the strings package but take and return []byte.
bytes.Contains([]byte("gopher"), []byte("ph")) // true
bytes.Index([]byte("gopher"), []byte("ph")) // 2
bytes.HasPrefix([]byte("gopher"), []byte("go")) // true
bytes.Split([]byte("a,b,c"), []byte(",")) // [[97] [98] [99]]
bytes.Fields([]byte(" hi there ")) // [[104 105] [116 104 101 114 101]]
bytes.Join([][]byte{{'a'}, {'b'}}, []byte("-")) // "a-b"
bytes.ToUpper([]byte("Go")) // "GO"
bytes.TrimSpace([]byte(" hi\n")) // "hi"
bytes.ReplaceAll([]byte("aaa"), []byte("a"), []byte("b")) // "bbb"
Faster than string(a) == string(b) because it skips the allocation. Safe with crypto/subtle's ConstantTimeCompare for secrets.
bytes.Equal([]byte("a"), []byte("a")) // true
Implements io.Reader and io.Writer. Zero value is ready to use.
var b bytes.Buffer
b.WriteString("hello")
b.WriteByte(' ')
fmt.Fprintf(&b, "%d", 42)
fmt.Println(b.String()) // "hello 42"
fmt.Println(b.Len()) // 8
hello 42
8
b := bytes.NewBufferString("one\ntwo\n")
scanner := bufio.NewScanner(b)
for scanner.Scan() {
fmt.Println("line:", scanner.Text())
}
line: one
line: two
Call Reset to clear the buffer for reuse without throwing the underlying slice away.
var b bytes.Buffer
b.WriteString("first")
b.Reset()
b.WriteString("second")
fmt.Println(b.String())
second
r := bytes.NewReader([]byte("hello world"))
r.Seek(6, io.SeekStart)
buf := make([]byte, 5)
r.Read(buf)
fmt.Println(string(buf))
world