Movatterモバイル変換


[0]ホーム

URL:


bytes

packagestandard library
go1.25.2Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2025 License:BSD-3-ClauseImports:8Imported by:1,185,103

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package bytes implements functions for the manipulation of byte slices.It is analogous to the facilities of thestrings package.

Index

Examples

Constants

View Source
const MinRead = 512

MinRead is the minimum slice size passed to aBuffer.Read call byBuffer.ReadFrom. As long as theBuffer has at least MinRead bytes beyondwhat is required to hold the contents of r,Buffer.ReadFrom will not grow theunderlying buffer.

Variables

View Source
var ErrTooLarge =errors.New("bytes.Buffer: too large")

ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.

Functions

funcCloneadded ingo1.20

func Clone(b []byte) []byte

Clone returns a copy of b[:len(b)].The result may have additional unused capacity.Clone(nil) returns nil.

Example
package mainimport ("bytes""fmt")func main() {b := []byte("abc")clone := bytes.Clone(b)fmt.Printf("%s\n", clone)clone[0] = 'd'fmt.Printf("%s\n", b)fmt.Printf("%s\n", clone)}
Output:abcabcdbc

funcCompare

func 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.

Example
package mainimport ("bytes")func main() {// Interpret Compare's result by comparing it to zero.var a, b []byteif 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}}

Example (Search)
package mainimport ("bytes""slices")func main() {// Binary search to find a matching byte slice.var needle []bytevar haystack [][]byte // Assume sorted_, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare)if found {// Found it!}}

funcContains

func Contains(b, subslice []byte)bool

Contains reports whether subslice is within b.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))fmt.Println(bytes.Contains([]byte(""), []byte("")))}
Output:truefalsetruetrue

funcContainsAnyadded ingo1.7

func ContainsAny(b []byte, charsstring)bool

ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))fmt.Println(bytes.ContainsAny([]byte(""), ""))}
Output:truetruefalsefalse

funcContainsFuncadded ingo1.21.0

func ContainsFunc(b []byte, f func(rune)bool)bool

ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).

Example
package mainimport ("bytes""fmt")func main() {f := func(r rune) bool {return r >= 'a' && r <= 'z'}fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))fmt.Println(bytes.ContainsFunc([]byte("World"), f))}
Output:falsetrue

funcContainsRuneadded ingo1.7

func ContainsRune(b []byte, rrune)bool

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))fmt.Println(bytes.ContainsRune([]byte(""), '@'))}
Output:truefalsetruetruefalse

funcCount

func 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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune}
Output:35

funcCutadded ingo1.18

func Cut(s, sep []byte) (before, after []byte, foundbool)

Cut slices s around the first instance of sep,returning the text before and after sep.The found result reports whether sep appears in s.If sep does not appear in s, cut returns s, nil, false.

Cut returns slices of the original slice s, not copies.

Example
package mainimport ("bytes""fmt")func main() {show := func(s, sep string) {before, after, found := bytes.Cut([]byte(s), []byte(sep))fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)}show("Gopher", "Go")show("Gopher", "ph")show("Gopher", "er")show("Gopher", "Badger")}
Output:Cut("Gopher", "Go") = "", "pher", trueCut("Gopher", "ph") = "Go", "er", trueCut("Gopher", "er") = "Goph", "", trueCut("Gopher", "Badger") = "Gopher", "", false

funcCutPrefixadded ingo1.20

func CutPrefix(s, prefix []byte) (after []byte, foundbool)

CutPrefix returns s without the provided leading prefix byte sliceand reports whether it found the prefix.If s doesn't start with prefix, CutPrefix returns s, false.If prefix is the empty byte slice, CutPrefix returns s, true.

CutPrefix returns slices of the original slice s, not copies.

Example
package mainimport ("bytes""fmt")func main() {show := func(s, prefix string) {after, found := bytes.CutPrefix([]byte(s), []byte(prefix))fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)}show("Gopher", "Go")show("Gopher", "ph")}
Output:CutPrefix("Gopher", "Go") = "pher", trueCutPrefix("Gopher", "ph") = "Gopher", false

funcCutSuffixadded ingo1.20

func CutSuffix(s, suffix []byte) (before []byte, foundbool)

CutSuffix returns s without the provided ending suffix byte sliceand reports whether it found the suffix.If s doesn't end with suffix, CutSuffix returns s, false.If suffix is the empty byte slice, CutSuffix returns s, true.

CutSuffix returns slices of the original slice s, not copies.

Example
package mainimport ("bytes""fmt")func main() {show := func(s, suffix string) {before, found := bytes.CutSuffix([]byte(s), []byte(suffix))fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)}show("Gopher", "Go")show("Gopher", "er")}
Output:CutSuffix("Gopher", "Go") = "Gopher", falseCutSuffix("Gopher", "er") = "Goph", true

funcEqual

func Equal(a, b []byte)bool

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))}
Output:truefalse

funcEqualFold

func 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 generalform of case-insensitivity.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))}
Output:true

funcFields

func 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 spacecharacters, as defined byunicode.IsSpace, returning a slice of subslices of s or anempty slice if s contains only white space. Every element of the returned slice isnon-empty. UnlikeSplit, leading and trailing runs of white space charactersare discarded.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("Fields are: %q", bytes.Fields([]byte("  foo bar  baz   ")))}
Output:Fields are: ["foo" "bar" "baz"]

funcFieldsFunc

func 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) andreturns a slice of subslices of s. If all code points in s satisfy f(c), orlen(s) == 0, an empty slice is returned. Every element of the returned slice isnon-empty. Unlike [SplitFunc], leading and trailing runs of code pointssatisfying f(c) are discarded.

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.

Example
package mainimport ("bytes""fmt""unicode")func main() {f := func(c rune) bool {return !unicode.IsLetter(c) && !unicode.IsNumber(c)}fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte("  foo1;bar2,baz3..."), f))}
Output:Fields are: ["foo1" "bar2" "baz3"]

funcFieldsFuncSeqadded ingo1.24.0

func FieldsFuncSeq(s []byte, f func(rune)bool)iter.Seq[[]byte]

FieldsFuncSeq returns an iterator over subslices of s split around runs ofUnicode code points satisfying f(c).The iterator yields the same subslices that would be returned byFieldsFunc(s),but without constructing a new slice containing the subslices.

Example
package mainimport ("bytes""fmt""unicode")func main() {text := []byte("The quick brown fox")fmt.Println("Split on whitespace(similar to FieldsSeq):")for word := range bytes.FieldsFuncSeq(text, unicode.IsSpace) {fmt.Printf("%q\n", word)}mixedText := []byte("abc123def456ghi")fmt.Println("\nSplit on digits:")for word := range bytes.FieldsFuncSeq(mixedText, unicode.IsDigit) {fmt.Printf("%q\n", word)}}
Output:Split on whitespace(similar to FieldsSeq):"The""quick""brown""fox"Split on digits:"abc""def""ghi"

funcFieldsSeqadded ingo1.24.0

func FieldsSeq(s []byte)iter.Seq[[]byte]

FieldsSeq returns an iterator over subslices of s split around runs ofwhitespace characters, as defined byunicode.IsSpace.The iterator yields the same subslices that would be returned byFields(s),but without constructing a new slice containing the subslices.

Example
package mainimport ("bytes""fmt")func main() {text := []byte("The quick brown fox")fmt.Println("Split byte slice into fields:")for word := range bytes.FieldsSeq(text) {fmt.Printf("%q\n", word)}textWithSpaces := []byte("  lots   of   spaces  ")fmt.Println("\nSplit byte slice with multiple spaces:")for word := range bytes.FieldsSeq(textWithSpaces) {fmt.Printf("%q\n", word)}}
Output:Split byte slice into fields:"The""quick""brown""fox"Split byte slice with multiple spaces:"lots""of""spaces"

funcHasPrefix

func HasPrefix(s, prefix []byte)bool

HasPrefix reports whether the byte slice s begins with prefix.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))}
Output:truefalsetrue

funcHasSuffix

func HasSuffix(s, suffix []byte)bool

HasSuffix reports whether the byte slice s ends with suffix.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))}
Output:truefalsefalsetrue

funcIndex

func 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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))}
Output:4-1

funcIndexAny

func IndexAny(s []byte, charsstring)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 Unicodecode points in chars. It returns -1 if chars is empty or if there is no codepoint in common.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))}
Output:2-1

funcIndexByte

func IndexByte(b []byte, cbyte)int

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))}
Output:4-1

funcIndexFunc

func IndexFunc(s []byte, f func(rrune)bool)int

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

Example
package mainimport ("bytes""fmt""unicode")func main() {f := func(c rune) bool {return unicode.Is(unicode.Han, c)}fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))}
Output:7-1

funcIndexRune

func IndexRune(s []byte, rrune)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 isutf8.RuneError, it returns the first instance of anyinvalid UTF-8 byte sequence.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))}
Output:4-1

funcJoin

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

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

Example
package mainimport ("bytes""fmt")func main() {s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}fmt.Printf("%s", bytes.Join(s, []byte(", ")))}
Output:foo, bar, baz

funcLastIndex

func 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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))}
Output:03-1

funcLastIndexAny

func LastIndexAny(s []byte, charsstring)int

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))}
Output:53-1

funcLastIndexByteadded ingo1.5

func LastIndexByte(s []byte, cbyte)int

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))}
Output:38-1

funcLastIndexFunc

func LastIndexFunc(s []byte, f func(rrune)bool)int

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

Example
package mainimport ("bytes""fmt""unicode")func main() {fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))}
Output:89-1

funcLinesadded ingo1.24.0

func Lines(s []byte)iter.Seq[[]byte]

Lines returns an iterator over the newline-terminated lines in the byte slice s.The lines yielded by the iterator include their terminating newlines.If s is empty, the iterator yields no lines at all.If s does not end in a newline, the final yielded line will not end in a newline.It returns a single-use iterator.

Example
package mainimport ("bytes""fmt")func main() {text := []byte("Hello\nWorld\nGo Programming\n")for line := range bytes.Lines(text) {fmt.Printf("%q\n", line)}}
Output:"Hello\n""World\n""Go Programming\n"

funcMap

func Map(mapping func(rrune)rune, s []byte) []byte

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

Example
package mainimport ("bytes""fmt")func main() {rot13 := func(r rune) rune {switch {case r >= 'A' && r <= 'Z':return 'A' + (r-'A'+13)%26case r >= 'a' && r <= 'z':return 'a' + (r-'a'+13)%26}return r}fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))}
Output:'Gjnf oevyyvt naq gur fyvgul tbcure...

funcRepeat

func Repeat(b []byte, countint) []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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))}
Output:banana

funcReplace

func Replace(s, old, new []byte, nint) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))}
Output:oinky oinky oinkmoo moo moo

funcReplaceAlladded ingo1.12

func ReplaceAll(s, old, new []byte) []byte

ReplaceAll returns a copy of the slice s with allnon-overlapping instances of old replaced by new.If old is empty, it matches at the beginning of the sliceand after each UTF-8 sequence, yielding up to k+1 replacementsfor a k-rune slice.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))}
Output:moo moo moo

funcRunes

func 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.

Example
package mainimport ("bytes""fmt")func main() {rs := bytes.Runes([]byte("go gopher"))for _, r := range rs {fmt.Printf("%#U\n", r)}}
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'

funcSplit

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

Split slices s into all subslices separated by sep and returns a slice ofthe 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, seeCut.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))}
Output:["a" "b" "c"]["" "man " "plan " "canal panama"][" " "x" "y" "z" " "][""]

funcSplitAfter

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

SplitAfter slices s into all subslices after each instance of sep andreturns 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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))}
Output:["a," "b," "c"]

funcSplitAfterN

func SplitAfterN(s, sep []byte, nint) [][]byte

SplitAfterN slices s into subslices after each instance of sep andreturns 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.
Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))}
Output:["a," "b,c"]

funcSplitAfterSeqadded ingo1.24.0

func SplitAfterSeq(s, sep []byte)iter.Seq[[]byte]

SplitAfterSeq returns an iterator over subslices of s split after each instance of sep.The iterator yields the same subslices that would be returned bySplitAfter(s, sep),but without constructing a new slice containing the subslices.It returns a single-use iterator.

Example
package mainimport ("bytes""fmt")func main() {s := []byte("a,b,c,d")for part := range bytes.SplitAfterSeq(s, []byte(",")) {fmt.Printf("%q\n", part)}}
Output:"a,""b,""c,""d"

funcSplitN

func SplitN(s, sep []byte, nint) [][]byte

SplitN slices s into subslices separated by sep and returns a slice ofthe 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, seeCut.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)fmt.Printf("%q (nil = %v)\n", z, z == nil)}
Output:["a" "b,c"][] (nil = true)

funcSplitSeqadded ingo1.24.0

func SplitSeq(s, sep []byte)iter.Seq[[]byte]

SplitSeq returns an iterator over all subslices of s separated by sep.The iterator yields the same subslices that would be returned bySplit(s, sep),but without constructing a new slice containing the subslices.It returns a single-use iterator.

Example
package mainimport ("bytes""fmt")func main() {s := []byte("a,b,c,d")for part := range bytes.SplitSeq(s, []byte(",")) {fmt.Printf("%q\n", part)}}
Output:"a""b""c""d"

funcTitledeprecated

func Title(s []byte) []byte

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

Deprecated: The rule Title uses for word boundaries does not handle Unicodepunctuation properly. Use golang.org/x/text/cases instead.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s", bytes.Title([]byte("her royal highness")))}
Output:Her Royal Highness

funcToLower

func ToLower(s []byte) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))}
Output:gopher

funcToLowerSpecial

func ToLowerSpecial(cunicode.SpecialCase, s []byte) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {str := []byte("AHOJ VÝVOJÁRİ GOLANG")totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)fmt.Println("Original : " + string(str))fmt.Println("ToLower : " + string(totitle))}
Output:Original : AHOJ VÝVOJÁRİ GOLANGToLower : ahoj vývojári golang

funcToTitle

func 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.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))fmt.Printf("%s\n", bytes.ToTitle([]byte("брат")))}
Output:LOUD NOISESБРАТ

funcToTitleSpecial

func ToTitleSpecial(cunicode.SpecialCase, s []byte) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {str := []byte("ahoj vývojári golang")totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)fmt.Println("Original : " + string(str))fmt.Println("ToTitle : " + string(totitle))}
Output:Original : ahoj vývojári golangToTitle : AHOJ VÝVOJÁRİ GOLANG

funcToUpper

func ToUpper(s []byte) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))}
Output:GOPHER

funcToUpperSpecial

func ToUpperSpecial(cunicode.SpecialCase, s []byte) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {str := []byte("ahoj vývojári golang")totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)fmt.Println("Original : " + string(str))fmt.Println("ToUpper : " + string(totitle))}
Output:Original : ahoj vývojári golangToUpper : AHOJ VÝVOJÁRİ GOLANG

funcToValidUTF8added ingo1.13

func ToValidUTF8(s, replacement []byte) []byte

ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytesrepresenting invalid UTF-8 replaced with the bytes in replacement, which may be empty.

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))}
Output:abcabcabc

funcTrim

func Trim(s []byte, cutsetstring) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))}
Output:["Achtung! Achtung"]

funcTrimFunc

func TrimFunc(s []byte, f func(rrune)bool) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))}
Output:-gopher!"go-gopher!"go-gophergo-gopher!

funcTrimLeft

func TrimLeft(s []byte, cutsetstring) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))}
Output:gopher8257

funcTrimLeftFunc

func TrimLeftFunc(s []byte, f func(rrune)bool) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))}
Output:-gophergo-gopher!go-gopher!567

funcTrimPrefixadded ingo1.1

func 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.

Example
package mainimport ("bytes""fmt")func main() {var b = []byte("Goodbye,, world!")b = bytes.TrimPrefix(b, []byte("Goodbye,"))b = bytes.TrimPrefix(b, []byte("See ya,"))fmt.Printf("Hello%s", b)}
Output:Hello, world!

funcTrimRight

func TrimRight(s []byte, cutsetstring) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))}
Output:453gopher

funcTrimRightFunc

func TrimRightFunc(s []byte, f func(rrune)bool) []byte

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

Example
package mainimport ("bytes""fmt""unicode")func main() {fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))}
Output:go-go-gopher1234go-gopher!

funcTrimSpace

func TrimSpace(s []byte) []byte

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))}
Output:a lone gopher

funcTrimSuffixadded ingo1.1

func 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.

Example
package mainimport ("bytes""os")func main() {var b = []byte("Hello, goodbye, etc!")b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))b = bytes.TrimSuffix(b, []byte("gopher"))b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)os.Stdout.Write(b)}
Output:Hello, world!

Types

typeBuffer

type Buffer struct {// contains filtered or unexported fields}

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

Example
package mainimport ("bytes""fmt""os")func main() {var b bytes.Buffer // A Buffer needs no initialization.b.Write([]byte("Hello "))fmt.Fprintf(&b, "world!")b.WriteTo(os.Stdout)}
Output:Hello world!

Example (Reader)
package mainimport ("bytes""encoding/base64""io""os")func main() {// A Buffer can turn a string or a []byte into an io.Reader.buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")dec := base64.NewDecoder(base64.StdEncoding, buf)io.Copy(os.Stdout, dec)}
Output:Gophers rule!

funcNewBuffer

func NewBuffer(buf []byte) *Buffer

NewBuffer creates and initializes a newBuffer using buf as itsinitial contents. The newBuffer takes ownership of buf, and thecaller should not use buf after this call. NewBuffer is intended toprepare aBuffer to read existing data. It can also be used to setthe 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 aBuffer variable) issufficient to initialize aBuffer.

funcNewBufferString

func NewBufferString(sstring) *Buffer

NewBufferString creates and initializes a newBuffer using string s as itsinitial contents. It is intended to prepare a buffer to read an existingstring.

In most cases, new(Buffer) (or just declaring aBuffer variable) issufficient to initialize aBuffer.

func (*Buffer)Availableadded ingo1.21.0

func (b *Buffer) Available()int

Available returns how many bytes are unused in the buffer.

func (*Buffer)AvailableBufferadded ingo1.21.0

func (b *Buffer) AvailableBuffer() []byte

AvailableBuffer returns an empty buffer with b.Available() capacity.This buffer is intended to be appended to andpassed to an immediately succeedingBuffer.Write call.The buffer is only valid until the next write operation on b.

Example
package mainimport ("bytes""os""strconv")func main() {var buf bytes.Bufferfor i := 0; i < 4; i++ {b := buf.AvailableBuffer()b = strconv.AppendInt(b, int64(i), 10)b = append(b, ' ')buf.Write(b)}os.Stdout.Write(buf.Bytes())}
Output:0 1 2 3

func (*Buffer)Bytes

func (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 likeBuffer.Read,Buffer.Write,Buffer.Reset, orBuffer.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.

Example
package mainimport ("bytes""os")func main() {buf := bytes.Buffer{}buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})os.Stdout.Write(buf.Bytes())}
Output:hello world

func (*Buffer)Capadded ingo1.5

func (b *Buffer) Cap()int

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

Example
package mainimport ("bytes""fmt")func main() {buf1 := bytes.NewBuffer(make([]byte, 10))buf2 := bytes.NewBuffer(make([]byte, 0, 10))fmt.Println(buf1.Cap())fmt.Println(buf2.Cap())}
Output:1010

func (*Buffer)Growadded ingo1.1

func (b *Buffer) Grow(nint)

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

Example
package mainimport ("bytes""fmt")func main() {var b bytes.Bufferb.Grow(64)bb := b.Bytes()b.Write([]byte("64 bytes or fewer"))fmt.Printf("%q", bb[:b.Len()])}
Output:"64 bytes or fewer"

func (*Buffer)Len

func (b *Buffer) Len()int

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

Example
package mainimport ("bytes""fmt")func main() {var b bytes.Bufferb.Grow(64)b.Write([]byte("abcde"))fmt.Printf("%d", b.Len())}
Output:5

func (*Buffer)Next

func (b *Buffer) Next(nint) []byte

Next returns a slice containing the next n bytes from the buffer,advancing the buffer as if the bytes had been returned byBuffer.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.

Example
package mainimport ("bytes""fmt")func main() {var b bytes.Bufferb.Grow(64)b.Write([]byte("abcde"))fmt.Printf("%s\n", b.Next(2))fmt.Printf("%s\n", b.Next(2))fmt.Printf("%s", b.Next(2))}
Output:abcde

func (*Buffer)Read

func (b *Buffer) Read(p []byte) (nint, errerror)

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

Example
package mainimport ("bytes""fmt")func main() {var b bytes.Bufferb.Grow(64)b.Write([]byte("abcde"))rdbuf := make([]byte, 1)n, err := b.Read(rdbuf)if err != nil {panic(err)}fmt.Println(n)fmt.Println(b.String())fmt.Println(string(rdbuf))}
Output:1bcdea

func (*Buffer)ReadByte

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

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

Example
package mainimport ("bytes""fmt")func main() {var b bytes.Bufferb.Grow(64)b.Write([]byte("abcde"))c, err := b.ReadByte()if err != nil {panic(err)}fmt.Println(c)fmt.Println(b.String())}
Output:97bcde

func (*Buffer)ReadBytes

func (b *Buffer) ReadBytes(delimbyte) (line []byte, errerror)

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 (oftenio.EOF).ReadBytes returns err != nil if and only if the returned data does not end indelim.

func (*Buffer)ReadFrom

func (b *Buffer) ReadFrom(rio.Reader) (nint64, errerror)

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

func (*Buffer)ReadRune

func (b *Buffer) ReadRune() (rrune, sizeint, errerror)

ReadRune reads and returns the next UTF-8-encodedUnicode 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, itconsumes one byte and returns U+FFFD, 1.

func (*Buffer)ReadString

func (b *Buffer) ReadString(delimbyte) (linestring, errerror)

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 (oftenio.EOF).ReadString returns err != nil if and only if the returned data does not endin delim.

func (*Buffer)Reset

func (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 asBuffer.Truncate(0).

func (*Buffer)String

func (b *Buffer) String()string

String returns the contents of the unread portion of the bufferas a string. If theBuffer is a nil pointer, it returns "<nil>".

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

func (*Buffer)Truncate

func (b *Buffer) Truncate(nint)

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

func (*Buffer)UnreadByte

func (b *Buffer) UnreadByte()error

UnreadByte unreads the last byte returned by the most recent successfulread operation that read at least one byte. If a write has happened sincethe last read, if the last read returned an error, or if the read read zerobytes, UnreadByte returns an error.

func (*Buffer)UnreadRune

func (b *Buffer) UnreadRune()error

UnreadRune unreads the last rune returned byBuffer.ReadRune.If the most recent read or write operation on the buffer wasnot a successfulBuffer.ReadRune, UnreadRune returns an error. (In this regardit is stricter thanBuffer.UnreadByte, which will unread the last bytefrom any read operation.)

func (*Buffer)Write

func (b *Buffer) Write(p []byte) (nint, errerror)

Write appends the contents of p to the buffer, growing the buffer asneeded. The return value n is the length of p; err is always nil. If thebuffer becomes too large, Write will panic withErrTooLarge.

func (*Buffer)WriteByte

func (b *Buffer) WriteByte(cbyte)error

WriteByte appends the byte c to the buffer, growing the buffer as needed.The returned error is always nil, but is included to matchbufio.Writer'sWriteByte. If the buffer becomes too large, WriteByte will panic withErrTooLarge.

func (*Buffer)WriteRune

func (b *Buffer) WriteRune(rrune) (nint, errerror)

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

func (*Buffer)WriteString

func (b *Buffer) WriteString(sstring) (nint, errerror)

WriteString appends the contents of s to the buffer, growing the buffer asneeded. The return value n is the length of s; err is always nil. If thebuffer becomes too large, WriteString will panic withErrTooLarge.

func (*Buffer)WriteTo

func (b *Buffer) WriteTo(wio.Writer) (nint64, errerror)

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 anint, but it is int64 to match theio.WriterTo interface. Any errorencountered during the write is also returned.

typeReader

type Reader struct {// contains filtered or unexported fields}

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

funcNewReader

func NewReader(b []byte) *Reader

NewReader returns a newReader reading from b.

func (*Reader)Len

func (r *Reader) Len()int

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

Example
package mainimport ("bytes""fmt")func main() {fmt.Println(bytes.NewReader([]byte("Hi!")).Len())fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())}
Output:316

func (*Reader)Read

func (r *Reader) Read(b []byte) (nint, errerror)

Read implements theio.Reader interface.

func (*Reader)ReadAt

func (r *Reader) ReadAt(b []byte, offint64) (nint, errerror)

ReadAt implements theio.ReaderAt interface.

func (*Reader)ReadByte

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

ReadByte implements theio.ByteReader interface.

func (*Reader)ReadRune

func (r *Reader) ReadRune() (chrune, sizeint, errerror)

ReadRune implements theio.RuneReader interface.

func (*Reader)Resetadded ingo1.7

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

Reset resets theReader to be reading from b.

func (*Reader)Seek

func (r *Reader) Seek(offsetint64, whenceint) (int64,error)

Seek implements theio.Seeker interface.

func (*Reader)Sizeadded ingo1.5

func (r *Reader) Size()int64

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

func (*Reader)UnreadByte

func (r *Reader) UnreadByte()error

UnreadByte complementsReader.ReadByte in implementing theio.ByteScanner interface.

func (*Reader)UnreadRune

func (r *Reader) UnreadRune()error

UnreadRune complementsReader.ReadRune in implementing theio.RuneScanner interface.

func (*Reader)WriteToadded ingo1.1

func (r *Reader) WriteTo(wio.Writer) (nint64, errerror)

WriteTo implements theio.WriterTo interface.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp