bytes

Package bytes implements functions for the manipulation of byte slices.

Index

Functions

func Compare

1func Compare(a, b []byte) int

Compare returns an integer comparing two byte slices lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b. A nil argument is equivalent to an empty slice.

 1// Interpret Compare's result by comparing it to zero.
 2var a, b []byte
 3if bytes.Compare(a, b) < 0 {
 4
 5}
 6if bytes.Compare(a, b) <= 0 {
 7
 8}
 9if bytes.Compare(a, b) > 0 {
10
11}
12if bytes.Compare(a, b) >= 0 {
13
14}
15
16if bytes.Equal(a, b) {
17
18}
19if !bytes.Equal(a, b) {
20
21}

 1// Binary search to find a matching byte slice.
 2var needle []byte
 3var haystack [][]byte	// Assume sorted
 4i := sort.Search(len(haystack), func(i int) bool {
 5
 6	return bytes.Compare(haystack[i], needle) >= 0
 7})
 8if i < len(haystack) && bytes.Equal(haystack[i], needle) {
 9
10}

func Contains

1func Contains(b, subslice []byte) bool

Contains reports whether subslice is within b.

1fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
2fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
3fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
4fmt.Println(bytes.Contains([]byte(""), []byte("")))

Output

true
false
true
true

func ContainsRune

1func ContainsRune(b []byte, r rune) bool

ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.

1fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
2fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
3fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
4fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
5fmt.Println(bytes.ContainsRune([]byte(""), '@'))

Output

true
false
true
true
false

func Count

1func Count(s, sep []byte) int

Count counts the number of non-overlapping instances of sep in s. If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.

1fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
2fmt.Println(bytes.Count([]byte("five"), []byte("")))

Output

3
5

func Equal

1func Equal(a, b []byte) bool

Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

1fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
2fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))

Output

true
false

func EqualFold

1func EqualFold(s, t []byte) bool

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

1fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))

Output

true

func Fields

1func Fields(s []byte) [][]byte

Fields interprets s as a sequence of UTF-8-encoded code points. It splits the slice s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of subslices of s or an empty slice if s contains only white space.

1fmt.Printf("Fields are: %q", bytes.Fields([]byte("  foo bar  baz   ")))

Output

Fields are: ["foo" "bar" "baz"]

func FieldsFunc

1func FieldsFunc(s []byte, f func(rune) bool) [][]byte

FieldsFunc interprets s as a sequence of UTF-8-encoded code points. It splits the slice s at each run of code points c satisfying f(c) and returns a slice of subslices of s. If all code points in s satisfy f(c), or len(s) == 0, an empty slice is returned.

FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

1f := func(c rune) bool {
2	return !unicode.IsLetter(c) && !unicode.IsNumber(c)
3}
4fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte("  foo1;bar2,baz3..."), f))

Output

Fields are: ["foo1" "bar2" "baz3"]

func HasPrefix

1func HasPrefix(s, prefix []byte) bool

HasPrefix tests whether the byte slice s begins with prefix.

1fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
2fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
3fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))

Output

true
false
true

func HasSuffix

1func HasSuffix(s, suffix []byte) bool

HasSuffix tests whether the byte slice s ends with suffix.

1fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
2fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
3fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
4fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))

Output

true
false
false
true

func Index

1func Index(s, sep []byte) int

Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.

1fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
2fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))

Output

4
-1

func IndexAny

1func IndexAny(s []byte, chars string) int

IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the first occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

1fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
2fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))

Output

2
-1

func IndexByte

1func IndexByte(b []byte, c byte) int

IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.

1fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
2fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))

Output

4
-1

func IndexFunc

1func IndexFunc(s []byte, f func(r rune) bool) int

IndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.

1f := func(c rune) bool {
2	return unicode.Is(unicode.Han, c)
3}
4fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
5fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))

Output

7
-1

func IndexRune

1func IndexRune(s []byte, r rune) int

IndexRune interprets s as a sequence of UTF-8-encoded code points. It returns the byte index of the first occurrence in s of the given rune. It returns -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

1fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
2fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))

Output

4
-1

func Join

1func Join(s [][]byte, sep []byte) []byte

Join concatenates the elements of s to create a new byte slice. The separator sep is placed between elements in the resulting slice.

1s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
2fmt.Printf("%s", bytes.Join(s, []byte(", ")))

Output

foo, bar, baz

func LastIndex

1func LastIndex(s, sep []byte) int

LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.

1fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
2fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
3fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))

Output

0
3
-1

func LastIndexAny

1func LastIndexAny(s []byte, chars string) int

LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the last occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

1fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
2fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
3fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))

Output

5
3
-1

func LastIndexByte

1func LastIndexByte(s []byte, c byte) int

LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

1fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
2fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
3fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))

Output

3
8
-1

func LastIndexFunc

1func LastIndexFunc(s []byte, f func(r rune) bool) int

LastIndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the last Unicode code point satisfying f(c), or -1 if none do.

1fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
2fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
3fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))

Output

8
9
-1

func Map

1func Map(mapping func(r rune) rune, s []byte) []byte

Map returns a copy of the byte slice s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the byte slice with no replacement. The characters in s and the output are interpreted as UTF-8-encoded code points.

func Repeat

1func Repeat(b []byte, count int) []byte

Repeat returns a new byte slice consisting of count copies of b.

It panics if count is negative or if the result of (len(b) * count) overflows.

1fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))

Output

banana

func Replace

1func Replace(s, old, new []byte, n int) []byte

Replace returns a copy of the slice s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice. If n < 0, there is no limit on the number of replacements.

1fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
2fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))

Output

oinky oinky oink
moo moo moo

func Runes

1func Runes(s []byte) []rune

Runes interprets s as a sequence of UTF-8-encoded code points. It returns a slice of runes (Unicode code points) equivalent to s.

1rs := bytes.Runes([]byte("go gopher"))
2for _, r := range rs {
3	fmt.Printf("%#U\n", r)
4}

Output

U+0067 'g'
U+006F 'o'
U+0020 ' '
U+0067 'g'
U+006F 'o'
U+0070 'p'
U+0068 'h'
U+0065 'e'
U+0072 'r'

func Split

1func Split(s, sep []byte) [][]byte

Split slices s into all subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, Split splits after each UTF-8 sequence. It is equivalent to SplitN with a count of -1.

To split around the first instance of a separator, see Cut.

1fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
2fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
3fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
4fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))

Output

["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]

func SplitAfter

1func SplitAfter(s, sep []byte) [][]byte

SplitAfter slices s into all subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfter splits after each UTF-8 sequence. It is equivalent to SplitAfterN with a count of -1.

1fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))

Output

["a," "b," "c"]

func SplitAfterN

1func SplitAfterN(s, sep []byte, n int) [][]byte

SplitAfterN slices s into subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfterN splits after each UTF-8 sequence. The count determines the number of subslices to return:

n > 0: at most n subslices; the last subslice will be the unsplit remainder.
n == 0: the result is nil (zero subslices)
n < 0: all subslices

1fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))

Output

["a," "b,c"]

func SplitN

1func SplitN(s, sep []byte, n int) [][]byte

SplitN slices s into subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, SplitN splits after each UTF-8 sequence. The count determines the number of subslices to return:

n > 0: at most n subslices; the last subslice will be the unsplit remainder.
n == 0: the result is nil (zero subslices)
n < 0: all subslices

To split around the first instance of a separator, see Cut.

1fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
2z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
3fmt.Printf("%q (nil = %v)\n", z, z == nil)

Output

["a" "b,c"]
[] (nil = true)

func ToLower

1func ToLower(s []byte) []byte

ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case.

1fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))

Output

gopher

func ToLowerSpecial

1func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte

ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their lower case, giving priority to the special casing rules.

1str := []byte("AHOJ VÝVOJÁRİ GOLANG")
2totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
3fmt.Println("Original : " + string(str))
4fmt.Println("ToLower : " + string(totitle))

Output

Original : AHOJ VÝVOJÁRİ GOLANG
ToLower : ahoj vývojári golang

func ToTitle

1func ToTitle(s []byte) []byte

ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.

1fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
2fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))

Output

LOUD NOISES
ХЛЕБ

func ToTitleSpecial

1func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte

ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case, giving priority to the special casing rules.

1str := []byte("ahoj vývojári golang")
2totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
3fmt.Println("Original : " + string(str))
4fmt.Println("ToTitle : " + string(totitle))

Output

Original : ahoj vývojári golang
ToTitle : AHOJ VÝVOJÁRİ GOLANG

func ToUpper

1func ToUpper(s []byte) []byte

ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case.

1fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))

Output

GOPHER

func ToUpperSpecial

1func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte

ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their upper case, giving priority to the special casing rules.

1str := []byte("ahoj vývojári golang")
2totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
3fmt.Println("Original : " + string(str))
4fmt.Println("ToUpper : " + string(totitle))

Output

Original : ahoj vývojári golang
ToUpper : AHOJ VÝVOJÁRİ GOLANG

func Trim

1func Trim(s []byte, cutset string) []byte

Trim returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in cutset.

1fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))

Output

["Achtung! Achtung"]

func TrimFunc

1func TrimFunc(s []byte, f func(r rune) bool) []byte

TrimFunc returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfy f(c).

1fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
2fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
3fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
4fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))

Output

-gopher!
"go-gopher!"
go-gopher
go-gopher!

func TrimLeft

1func TrimLeft(s []byte, cutset string) []byte

TrimLeft returns a subslice of s by slicing off all leading UTF-8-encoded code points contained in cutset.

1fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))

Output

gopher8257

func TrimLeftFunc

1func TrimLeftFunc(s []byte, f func(r rune) bool) []byte

TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off all leading UTF-8-encoded code points c that satisfy f(c).

1fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
2fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
3fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))

Output

-gopher
go-gopher!
go-gopher!567

func TrimPrefix

1func TrimPrefix(s, prefix []byte) []byte

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

1var b = []byte("Goodbye,, world!")
2b = bytes.TrimPrefix(b, []byte("Goodbye,"))
3b = bytes.TrimPrefix(b, []byte("See ya,"))
4fmt.Printf("Hello%s", b)

Output

Hello, world!

func TrimRight

1func TrimRight(s []byte, cutset string) []byte

TrimRight returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in cutset.

1fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))

Output

453gopher

func TrimRightFunc

1func TrimRightFunc(s []byte, f func(r rune) bool) []byte

TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8-encoded code points c that satisfy f(c).

1fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
2fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
3fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))

Output

go-
go-gopher
1234go-gopher!

func TrimSpace

1func TrimSpace(s []byte) []byte

TrimSpace returns a subslice of s by slicing off all leading and trailing white space, as defined by Unicode.

1fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))

Output

a lone gopher

func TrimSuffix

1func TrimSuffix(s, suffix []byte) []byte

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

1var b = []byte("Hello, goodbye, etc!")
2b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
3b = bytes.TrimSuffix(b, []byte("gopher"))
4b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
5os.Stdout.Write(b)

Output

Hello, world!

func NewBuffer

1func NewBuffer(buf []byte) *Buffer

NewBuffer creates and initializes a new Buffer using buf as its initial contents. The new Buffer takes ownership of buf, and the caller should not use buf after this call. NewBuffer is intended to prepare a Buffer to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func NewBufferString

1func NewBufferString(s string) *Buffer

NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func NewReader

1func NewReader(b []byte) *Reader

NewReader returns a new Reader reading from b.

Types

type Buffer

1type Buffer struct {
2}

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

func Bytes

1func (b *Buffer) Bytes() []byte

Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Read, Write, Reset, or Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

1buf := bytes.Buffer{}
2buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
3os.Stdout.Write(buf.Bytes())

Output

hello world

func Cap

1func (b *Buffer) Cap() int

Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.

1buf1 := bytes.NewBuffer(make([]byte, 10))
2buf2 := bytes.NewBuffer(make([]byte, 0, 10))
3fmt.Println(buf1.Cap())
4fmt.Println(buf2.Cap())

Output

10
10

func Grow

1func (b *Buffer) Grow(n int)

Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. If n is negative, Grow will panic. If the buffer can't grow it will panic with ErrTooLarge.

1var b bytes.Buffer
2b.Grow(64)
3bb := b.Bytes()
4b.Write([]byte("64 bytes or fewer"))
5fmt.Printf("%q", bb[:b.Len()])

Output

"64 bytes or fewer"

func Len

1func (b *Buffer) Len() int

Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

1var b bytes.Buffer
2b.Grow(64)
3b.Write([]byte("abcde"))
4fmt.Printf("%d", b.Len())

Output

5

func Next

1func (b *Buffer) Next(n int) []byte

Next returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.

1var b bytes.Buffer
2b.Grow(64)
3b.Write([]byte("abcde"))
4fmt.Printf("%s\n", string(b.Next(2)))
5fmt.Printf("%s\n", string(b.Next(2)))
6fmt.Printf("%s", string(b.Next(2)))

Output

ab
cd
e

func Read

1func (b *Buffer) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

 1var b bytes.Buffer
 2b.Grow(64)
 3b.Write([]byte("abcde"))
 4rdbuf := make([]byte, 1)
 5n, err := b.Read(rdbuf)
 6if err != nil {
 7	panic(err)
 8}
 9fmt.Println(n)
10fmt.Println(b.String())
11fmt.Println(string(rdbuf))

func ReadByte

1func (b *Buffer) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.

1var b bytes.Buffer
2b.Grow(64)
3b.Write([]byte("abcde"))
4c, err := b.ReadByte()
5if err != nil {
6	panic(err)
7}
8fmt.Println(c)
9fmt.Println(b.String())

func ReadBytes

1func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.

func ReadFrom

1func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

func ReadRune

1func (b *Buffer) ReadRune() (r rune, size int, err error)

ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

func ReadString

1func (b *Buffer) ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

func Reset

1func (b *Buffer) Reset()

Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

func String

1func (b *Buffer) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "".

To build strings more efficiently, see the strings.Builder type.

func Truncate

1func (b *Buffer) Truncate(n int)

Truncate discards all but the first n unread bytes from the buffer but continues to use the same allocated storage. It panics if n is negative or greater than the length of the buffer.

func UnreadByte

1func (b *Buffer) UnreadByte() error

UnreadByte unreads the last byte returned by the most recent successful read operation that read at least one byte. If a write has happened since the last read, if the last read returned an error, or if the read read zero bytes, UnreadByte returns an error.

func UnreadRune

1func (b *Buffer) UnreadRune() error

UnreadRune unreads the last rune returned by ReadRune. If the most recent read or write operation on the buffer was not a successful ReadRune, UnreadRune returns an error. (In this regard it is stricter than UnreadByte, which will unread the last byte from any read operation.)

func Write

1func (b *Buffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

func WriteByte

1func (b *Buffer) WriteByte(c byte) error

WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. If the buffer becomes too large, WriteByte will panic with ErrTooLarge.

func WriteRune

1func (b *Buffer) WriteRune(r rune) (n int, err error)

WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic with ErrTooLarge.

func WriteString

1func (b *Buffer) WriteString(s string) (n int, err error)

WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. If the buffer becomes too large, WriteString will panic with ErrTooLarge.

func WriteTo

1func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.

type Reader

1type Reader struct {
2}

A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice. Unlike a Buffer, a Reader is read-only and supports seeking. The zero value for Reader operates like a Reader of an empty slice.

func Len

1func (r *Reader) Len() int

Len returns the number of bytes of the unread portion of the slice.

1fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
2fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())

Output

3
16

func Read

1func (r *Reader) Read(b []byte) (n int, err error)

Read implements the io.Reader interface.

func ReadAt

1func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

ReadAt implements the io.ReaderAt interface.

func ReadByte

1func (r *Reader) ReadByte() (byte, error)

ReadByte implements the io.ByteReader interface.

func ReadRune

1func (r *Reader) ReadRune() (ch rune, size int, err error)

ReadRune implements the io.RuneReader interface.

func Reset

1func (r *Reader) Reset(b []byte)

Reset resets the Reader to be reading from b.

func Seek

1func (r *Reader) Seek(offset int64, whence int) (int64, error)

Seek implements the io.Seeker interface.

func Size

1func (r *Reader) Size() int64

Size returns the original length of the underlying byte slice. Size is the number of bytes available for reading via ReadAt. The result is unaffected by any method calls except Reset.

func UnreadByte

1func (r *Reader) UnreadByte() error

UnreadByte complements ReadByte in implementing the io.ByteScanner interface.

func UnreadRune

1func (r *Reader) UnreadRune() error

UnreadRune complements ReadRune in implementing the io.RuneScanner interface.

func WriteTo

1func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface.


© Matthias Hochgatterer – MastodonGithubRésumé