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

Documentation ¶

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

  • func Clone(b []byte) []byte
  • func Compare(a, b []byte) int
  • func Contains(b, subslice []byte) bool
  • func ContainsAny(b []byte, chars string) bool
  • func ContainsFunc(b []byte, f func(rune) bool) bool
  • func ContainsRune(b []byte, r rune) bool
  • func Count(s, sep []byte) int
  • func Cut(s, sep []byte) (before, after []byte, found bool)
  • func CutPrefix(s, prefix []byte) (after []byte, found bool)
  • func CutSuffix(s, suffix []byte) (before []byte, found bool)
  • func Equal(a, b []byte) bool
  • func EqualFold(s, t []byte) bool
  • func Fields(s []byte) [][]byte
  • func FieldsFunc(s []byte, f func(rune) bool) [][]byte
  • func HasPrefix(s, prefix []byte) bool
  • func HasSuffix(s, suffix []byte) bool
  • func Index(s, sep []byte) int
  • func IndexAny(s []byte, chars string) int
  • func IndexByte(b []byte, c byte) int
  • func IndexFunc(s []byte, f func(r rune) bool) int
  • func IndexRune(s []byte, r rune) int
  • func Join(s [][]byte, sep []byte) []byte
  • func LastIndex(s, sep []byte) int
  • func LastIndexAny(s []byte, chars string) int
  • func LastIndexByte(s []byte, c byte) int
  • func LastIndexFunc(s []byte, f func(r rune) bool) int
  • func Map(mapping func(r rune) rune, s []byte) []byte
  • func Repeat(b []byte, count int) []byte
  • func Replace(s, old, new []byte, n int) []byte
  • func ReplaceAll(s, old, new []byte) []byte
  • func Runes(s []byte) []rune
  • func Split(s, sep []byte) [][]byte
  • func SplitAfter(s, sep []byte) [][]byte
  • func SplitAfterN(s, sep []byte, n int) [][]byte
  • func SplitN(s, sep []byte, n int) [][]byte
  • func Title(s []byte) []byte deprecated
  • func ToLower(s []byte) []byte
  • func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte
  • func ToTitle(s []byte) []byte
  • func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte
  • func ToUpper(s []byte) []byte
  • func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte
  • func ToValidUTF8(s, replacement []byte) []byte
  • func Trim(s []byte, cutset string) []byte
  • func TrimFunc(s []byte, f func(r rune) bool) []byte
  • func TrimLeft(s []byte, cutset string) []byte
  • func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
  • func TrimPrefix(s, prefix []byte) []byte
  • func TrimRight(s []byte, cutset string) []byte
  • func TrimRightFunc(s []byte, f func(r rune) bool) []byte
  • func TrimSpace(s []byte) []byte
  • func TrimSuffix(s, suffix []byte) []byte
  • type Buffer
  • func NewBuffer(buf []byte) *Buffer
  • func NewBufferString(s string) *Buffer
  • func (b *Buffer) Available() int
  • func (b *Buffer) AvailableBuffer() []byte
  • func (b *Buffer) Bytes() []byte
  • func (b *Buffer) Cap() int
  • func (b *Buffer) Grow(n int)
  • func (b *Buffer) Len() int
  • func (b *Buffer) Next(n int) []byte
  • func (b *Buffer) Read(p []byte) (n int, err error)
  • func (b *Buffer) ReadByte() (byte, error)
  • func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
  • func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
  • func (b *Buffer) ReadRune() (r rune, size int, err error)
  • func (b *Buffer) ReadString(delim byte) (line string, err error)
  • func (b *Buffer) Reset()
  • func (b *Buffer) String() string
  • func (b *Buffer) Truncate(n int)
  • func (b *Buffer) UnreadByte() error
  • func (b *Buffer) UnreadRune() error
  • func (b *Buffer) Write(p []byte) (n int, err error)
  • func (b *Buffer) WriteByte(c byte) error
  • func (b *Buffer) WriteRune(r rune) (n int, err error)
  • func (b *Buffer) WriteString(s string) (n int, err error)
  • func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
  • type Reader
  • func NewReader(b []byte) *Reader
  • func (r *Reader) Len() int
  • func (r *Reader) Read(b []byte) (n int, err error)
  • func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
  • func (r *Reader) ReadByte() (byte, error)
  • func (r *Reader) ReadRune() (ch rune, size int, err error)
  • func (r *Reader) Reset(b []byte)
  • func (r *Reader) Seek(offset int64, whence int) (int64, error)
  • func (r *Reader) Size() int64
  • func (r *Reader) UnreadByte() error
  • func (r *Reader) UnreadRune() error
  • func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
  • Buffer (Reader)
  • Buffer.AvailableBuffer
  • Buffer.Bytes
  • Buffer.Grow
  • Buffer.Next
  • Buffer.Read
  • Buffer.ReadByte
  • Compare (Search)
  • ContainsAny
  • ContainsFunc
  • ContainsRune
  • LastIndexAny
  • LastIndexByte
  • LastIndexFunc
  • SplitAfterN
  • ToLowerSpecial
  • ToTitleSpecial
  • ToUpperSpecial
  • ToValidUTF8
  • TrimLeftFunc
  • TrimRightFunc

Constants ¶

MinRead is the minimum slice size passed to a Read call by Buffer.ReadFrom . As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, ReadFrom will not grow the underlying buffer.

Variables ¶

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

Functions ¶

Func clone ¶ added in go1.20.

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

func Compare ¶

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.

func Contains ¶

Contains reports whether subslice is within b.

func ContainsAny ¶ added in go1.7

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

func ContainsFunc ¶ added in go1.21.0

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

func ContainsRune ¶ added in go1.7

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

func Count ¶

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.

func Cut ¶ added in go1.18

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.

func CutPrefix ¶ added in go1.20

CutPrefix returns s without the provided leading prefix byte slice and 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.

func CutSuffix ¶ added in go1.20

CutSuffix returns s without the provided ending suffix byte slice and 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.

func Equal ¶

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

func EqualFold ¶

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.

func Fields ¶

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.

func FieldsFunc ¶

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.

func HasPrefix ¶

HasPrefix reports whether the byte slice s begins with prefix.

func HasSuffix ¶

HasSuffix reports whether the byte slice s ends with suffix.

func Index ¶

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

func IndexAny ¶

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.

func IndexByte ¶

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

func IndexFunc ¶

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.

func IndexRune ¶

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.

func Join ¶

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

func LastIndex ¶

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

func LastIndexAny ¶

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.

func LastIndexByte ¶ added in go1.5

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

func LastIndexFunc ¶

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.

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 ¶

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.

func Replace ¶

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.

func ReplaceAll ¶ added in go1.12

ReplaceAll returns a copy of the slice s with all 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.

func Runes ¶

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

func Split ¶

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.

func SplitAfter ¶

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.

func SplitAfterN ¶

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:

func SplitN ¶

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:

func Title deprecated

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

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

func ToLower ¶

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

func ToLowerSpecial ¶

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.

func ToTitle ¶

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

func ToTitleSpecial ¶

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.

func ToUpper ¶

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

func ToUpperSpecial ¶

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.

func ToValidUTF8 ¶ added in go1.13

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

func Trim ¶

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

func TrimFunc ¶

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

func TrimLeft ¶

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

func TrimLeftFunc ¶

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

func TrimPrefix ¶ added in go1.1

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

func TrimRight ¶

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

func TrimRightFunc ¶

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

func TrimSpace ¶

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

func TrimSuffix ¶ added in go1.1

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

type Buffer ¶

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

func NewBuffer ¶

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 ¶

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.

func (*Buffer) Available ¶ added in go1.21.0

Available returns how many bytes are unused in the buffer.

func (*Buffer) AvailableBuffer ¶ added in go1.21.0

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

func (*Buffer) Bytes ¶

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 Buffer.Read , Buffer.Write , Buffer.Reset , or Buffer.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.

func (*Buffer) Cap ¶ added in go1.5

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

func (*Buffer) Grow ¶ added in go1.1

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 .

func (*Buffer) Len ¶

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

func (*Buffer) Next ¶

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

func (*Buffer) Read ¶

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.

func (*Buffer) ReadByte ¶

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

func (*Buffer) ReadBytes ¶

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 (*Buffer) ReadFrom ¶

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 (*Buffer) ReadRune ¶

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 (*Buffer) ReadString ¶

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 (*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 Buffer.Truncate (0).

func (*Buffer) String ¶

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

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

func (*Buffer) Truncate ¶

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 (*Buffer) UnreadByte ¶

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 (*Buffer) UnreadRune ¶

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

func (*Buffer) Write ¶

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 (*Buffer) WriteByte ¶

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 (*Buffer) WriteRune ¶

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 (*Buffer) WriteString ¶

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 (*Buffer) WriteTo ¶

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 ¶

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 NewReader ¶

NewReader returns a new [Reader.Reader] reading from b.

func (*Reader) Len ¶

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

func (*Reader) Read ¶

Read implements the io.Reader interface.

func (*Reader) ReadAt ¶

ReadAt implements the io.ReaderAt interface.

func (*Reader) ReadByte ¶

ReadByte implements the io.ByteReader interface.

func (*Reader) ReadRune ¶

ReadRune implements the io.RuneReader interface.

func (*Reader) Reset ¶ added in go1.7

Reset resets the [Reader.Reader] to be reading from b.

func (*Reader) Seek ¶

Seek implements the io.Seeker interface.

func (*Reader) Size ¶ added in go1.5

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

func (*Reader) UnreadByte ¶

UnreadByte complements Reader.ReadByte in implementing the io.ByteScanner interface.

func (*Reader) UnreadRune ¶

UnreadRune complements Reader.ReadRune in implementing the io.RuneScanner interface.

func (*Reader) WriteTo ¶ added in go1.1

WriteTo implements the io.WriterTo interface.

Source Files ¶

Keyboard shortcuts.

TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

  • Golang Bytes: Slices and Methods

golang byte slice assignment

Result: As with strings.Index, bytes.Index returns the index if a sequence matches. Otherwise it returns -1.

golang byte slice assignment

Related Links:

  • Golang strconv, Convert Int to String
  • Golang Odd and Even Numbers
  • Golang Recover Built In: Handle Errors, Panics
  • Learn Go Language Tutorial
  • Golang html template Example
  • Golang http.Get Examples: Download Web Pages
  • Golang container list Example (Linked List)
  • Golang base64 Encoding Example: EncodeToString
  • Golang os exec Examples: Command Start and Run
  • Golang String Between, Before and After
  • Golang os.Remove: Delete All Files in Directory
  • Golang First Words in String
  • Golang flag Examples
  • Golang Regexp Find Examples: FindAllString
  • Golang Regexp Examples: MatchString, MustCompile
  • Golang Index, LastIndex: strings Funcs
  • Golang Compress GZIP Examples
  • Golang Interface Example
  • Golang 2D Slices and Arrays
  • Golang Sscan, Sscanf Examples (fmt)
  • Top 41 Go Programming (Golang) Interview Questions (2021)
  • Golang Padding String Example (Right or Left Align)
  • Golang Equal String, EqualFold (If Strings Are the Same)
  • Golang map Examples
  • Golang Map With String Slice Values
  • Golang Array Examples
  • Golang Remove Duplicates From Slice
  • Golang If, Else Statements
  • Golang ParseInt Examples: Convert String to Int
  • Golang Strings
  • Golang strings.Map func
  • Golang bufio.ScanBytes, NewScanner (Read Bytes in File)
  • Golang Built In Functions
  • Golang bytes.Buffer Examples (WriteString, Fprintf)
  • Golang Caesar Cipher Method
  • Golang Chan: Channels, Make Examples
  • Golang Math Module: math.Abs, Pow
  • Golang Reverse String
  • Golang Struct Examples: Types and Pointers
  • Golang path and filepath Examples (Base, Dir)
  • Golang Substring Examples (Rune Slices)
  • Golang Suffixarray Examples: New, Lookup Benchmark
  • Golang switch Examples
  • Golang Convert Map to Slice
  • Golang Convert Slice to String: int, string Slices
  • Golang Const, Var Examples: Iota
  • Golang ROT13 Method
  • Golang strings.Contains and ContainsAny
  • Golang rand, crypto: Random Number Generators
  • Golang String Literal Examples (Repeat Method)
  • Golang ToLower, ToUpper String Examples
  • Golang Trim, TrimSpace and TrimFunc Examples
  • Golang Join Examples (strings.Join)
  • Golang Len (String Length)
  • Golang Convert String to Rune Slice (append)
  • Golang JSON Example: Marshal, Unmarshal
  • Golang Replace String Examples: Replacer, NewReplacer
  • Golang nil (Cannot Use nil as Type)
  • Golang Slice Examples
  • Golang ListenAndServe Examples (HandleFunc)
  • Golang Fibonacci Sequence Example
  • Golang Time: Now, Parse and Duration
  • Golang bits, OnesCount (Get Bitcount From Int)
  • Golang Fprint, Fprintf and Fprintln Examples (fmt)
  • Golang Func Examples
  • Golang csv Examples
  • Golang Fields and FieldsFunc
  • Golang unicode.IsSpace (If Char Is Whitespace)
  • Golang fmt.Println Examples
  • Golang for Loop Examples: Foreach and While
  • Golang ioutil.WriteFile, os.Create (Write File to Disk)
  • Golang File Handling
  • Golang range: Slice, String and Map
  • Golang Readdir Example (Get All Files in Directory)
  • Golang Sort Slice: Len, Less, Swap in Interface
  • Golang Get Lines in File (String Slice)
  • Golang Split Examples (SplitAfter, SplitN)

Related Links

Package bytes

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

Package files

buffer.go bytes.go bytes_amd64.go bytes_decl.go reader.go

Internal call graph ▹

Internal call graph ▾.

In the call graph viewer below, each node is a function belonging to this package and its children are the functions it calls—perhaps dynamically.

The root nodes are the entry points of the package: functions that may be called from outside the package. There may be non-exported or anonymous functions among them if they are called dynamically from another package.

Click a node to visit that function's source code. From there you can visit its callers by clicking its declaring func token.

Functions may be omitted if they were determined to be unreachable in the particular programs or tests that were analyzed.

MinRead is the minimum slice size passed to a Read call by Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, ReadFrom will not grow the underlying buffer.

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

func Compare ¶

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 (Search)

▾ Example (Search)

func Contains ¶

Contains reports whether subslice is within b.

func ContainsAny ¶

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

func ContainsRune ¶

ContainsRune reports whether the Unicode code point r is within b.

func Count ¶

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

func Equal ¶

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

func EqualFold ¶

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under Unicode case-folding.

func Fields ¶

Fields splits the slice s around each instance of one or more consecutive white space characters, returning a slice of subslices of s or an empty list if s contains only white space.

func FieldsFunc ¶

FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode 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). If f does not return consistent results for a given c, FieldsFunc may crash.

func HasPrefix ¶

HasPrefix tests whether the byte slice s begins with prefix.

func HasSuffix ¶

HasSuffix tests whether the byte slice s ends with suffix.

func Index ¶

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

func IndexAny ¶

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.

func IndexByte ¶

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

func IndexFunc ¶

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

func IndexRune ¶

IndexRune interprets s as a sequence of UTF-8-encoded Unicode 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.

func Join ¶

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

func LastIndex ¶

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

func LastIndexAny ¶

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.

func LastIndexByte ¶

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

func LastIndexFunc ¶

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

func Map ¶

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 string with no replacement. The characters in s and the output are interpreted as UTF-8-encoded Unicode code points.

func Repeat ¶

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.

func Replace ¶

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.

func Runes ¶

Runes returns a slice of runes (Unicode code points) equivalent to s.

func Split ¶

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.

func SplitAfter ¶

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.

func SplitAfterN ¶

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:

func SplitN ¶

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:

func Title ¶

Title returns a copy of s with all Unicode letters that begin words mapped to their title case.

BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly.

func ToLower ¶

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

func ToLowerSpecial ¶

ToLowerSpecial returns a copy of the byte slice s with all Unicode letters mapped to their lower case, giving priority to the special casing rules.

func ToTitle ¶

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

func ToTitleSpecial ¶

ToTitleSpecial returns a copy of the byte slice s with all Unicode letters mapped to their title case, giving priority to the special casing rules.

func ToUpper ¶

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

func ToUpperSpecial ¶

ToUpperSpecial returns a copy of the byte slice s with all Unicode letters mapped to their upper case, giving priority to the special casing rules.

func Trim ¶

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

func TrimFunc ¶

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

func TrimLeft ¶

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

func TrimLeftFunc ¶

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

func TrimPrefix ¶

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

func TrimRight ¶

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

func TrimRightFunc ¶

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

func TrimSpace ¶

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

func TrimSuffix ¶

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

type Buffer ¶

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.

▹ Example (Reader)

▾ Example (Reader)

func NewBuffer ¶

NewBuffer creates and initializes a new Buffer using buf as its initial contents. It is intended to prepare a Buffer to read existing data. It can also be used to size 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 ¶

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.

func (*Buffer) Bytes ¶

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.

func (*Buffer) Cap ¶

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

func (*Buffer) Grow ¶

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.

func (*Buffer) Len ¶

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

func (*Buffer) Next ¶

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.

func (*Buffer) Read ¶

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.

func (*Buffer) ReadByte ¶

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

func (*Buffer) ReadBytes ¶

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 (*Buffer) ReadFrom ¶

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 (*Buffer) ReadRune ¶

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 (*Buffer) ReadString ¶

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 (*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 (*Buffer) String ¶

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

func (*Buffer) Truncate ¶

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 (*Buffer) UnreadByte ¶

UnreadByte unreads the last byte returned by the most recent read operation. If write has happened since the last read, UnreadByte returns an error.

func (*Buffer) UnreadRune ¶

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

func (*Buffer) Write ¶

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 (*Buffer) WriteByte ¶

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 (*Buffer) WriteRune ¶

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 (*Buffer) WriteString ¶

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 (*Buffer) WriteTo ¶

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 ¶

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.

func NewReader ¶

NewReader returns a new Reader reading from b.

func (*Reader) Len ¶

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

func (*Reader) Read ¶

Func (*reader) readat ¶, func (*reader) readbyte ¶, func (*reader) readrune ¶, func (*reader) reset ¶.

Reset resets the Reader to be reading from b.

func (*Reader) Seek ¶

Seek implements the io.Seeker interface.

func (*Reader) Size ¶

Size returns the original length of the underlying byte slice. Size is the number of bytes available for reading via ReadAt. The returned value is always the same and is not affected by calls to any other method.

func (*Reader) UnreadByte ¶

Func (*reader) unreadrune ¶, func (*reader) writeto ¶.

WriteTo implements the io.WriterTo interface.

The rule Title uses for word boundaries does not handle Unicode punctuation properly.

GoLang Topics

Golang slice.

Switch to English

Table of Contents

Introduction

What is a slice, arrays vs slices, creating and initializing a slice, appending to a slice, iterating over a slice, tips and common mistakes.

  • Slice is a variable-length sequence whose elements all have the same type. It's a reference to an underlying array. The slice data type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays.
  • Arrays are fixed-length sequence of items of the same type. The size of an array is a part of its type, so arrays cannot grow or shrink. On the other hand, slices are dynamically-sized, flexible view into the elements of an array. They are more commonly used than arrays because they can grow and shrink as needed.
  • The make function can be used to create a slice. This function takes three arguments: the type, length, and optional capacity. Here's a basic example: go s := make([]int, 10) In this example, we've created a slice of integers that has a length and capacity of 10.
  • Since slices are dynamic, we can add more elements to it using the append function. This function takes a slice and the elements to be added as arguments, and returns a slice. go s = append(s, 1, 2, 3) After this operation, the slice s will have a length of 13 and a capacity of 20.
  • We can use the range keyword to iterate over a slice. The range keyword returns two values: the index and the value at that index. go for i, v := range s { fmt.Printf("At index %d: %v\n", i, v) } This will print the index and value of each element in the slice.
  • When using the append function, remember that it may create a new underlying array to accommodate the new elements. This means that any references to the original slice will be unaffected by the append operation. If you want to modify the original slice, make sure to use the returned slice from the append function.
  • The zero value of a slice is nil. A nil slice has a length and capacity of 0. You can append values to a nil slice using the append function. Here's an example: go var s []int s = append(s, 1) In this example, we've appended 1 to the nil slice s.
  • Be careful when slicing slices. Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as regular array operations. However, it also means that if you modify the elements of a slice, it will affect the original array and all other slices that refer to it.

Popular Articles

  • Golang Initialize Struct (Jan 02, 2024)
  • Golang If Statement (Jan 02, 2024)
  • Golang Iterate Over Array (Jan 02, 2024)
  • Golang Foreach (Jan 02, 2024)
  • Golang Bytes.buffer (Jan 02, 2024)

Slices in Golang

Slices are resizable arrays that provide huge flexibility when working with it. In this post, we will see how to use slices in Golang.

Declaration of a slice

A slice is declared just like an array but without mentioning its size.

Difference between slices and arrays

Arrays, after declared of some size, cannot be resized, whereas slices can be resized. Slices are reference-types while arrays are value-type.

Creating slices in Golang

Noe, we will see how we can create slices for our usage. There are quite a few ways we can create a slice.

1. Using slice literal syntax

Slice literal is the initialization syntax of a slice. Below is an example of using slice literal syntax to create a slice.

2. Creating slices from an array

A slice has a reference to an array. So, it’s not difficult to create them from arrays. Here is how to do that.

Element high is excluded here.

3. Creating slices from another slice

Slices can be created from other slices by taking a slice of that slice.

4. Creating slices using make() function

There is a function in Go called make(), which can be used to create slices as well. Which takes in type of slice, length, and capacity of that slice.

The len() and cap() functions

The len() and cap() functions provide the length and capacity of a slice. To understand the difference between both, let’s see an example.

Zero-valued slices

The zero-valued slice is nil. That means its length and capacity is zero. Here is an example showing it.

Modifying values in slices

The modification of values inside slices is really simple. All we need to do is just assign data in that index or slice. Here is an example illustrating the ways it can be done.

Removing values from slices

To remove value at index i in a slice we can simply append elements up to index i and from i+1 to the end . This is what it looks like.

Passing slice to a function

When a slice is passed to a function and made changes inside it, the changes will be available outside as well. The reason behind this is that the slice is a reference type.

Slice functions

There are slice functions that make using slice even easier. Here are some important ones.

Slice of slices

We can create a slice of slices which is essentially a multidimensional slice.

Iterating over a slice elements

Iteration over a slice can be done using a for-range loop. We can use simple for loop along with len function also. Here is how to do that.

This is how we can use slices in Go.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

last modified August 24, 2023

Go byte tutorial shows how to work with bytes in Golang.

A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.

Go uses rune , which has type int32 , to deal with multibyte characters.

The bytes package implements functions for the manipulation of byte slices. It is similar to the strings package.

We use Go version 1.18.

Go byte example

In the next example, we work with simple bytes.

We have three bytes.

A byte is defined with the byte data type.

With the %c format verb, we print the character representation of the byte.

We must explicitly set a variable to the byte type; otherwise, we get different types.

In the code example, we have three variables.

The a variable has byte data type.

Because we have not set the data type explicitly, Go set a default int type.

Character literals are set to rune type (int32).

Go string to bytes

In the following example, we convert strings to bytes.

We convert two strings to bytes with []byte() typecast.

Go bytes to string

In the following example, we convert bytes to strings.

We convert a slice of bytes to a string with the string function.

Go count bytes

We count bytes with the len function. To count runes, we use the utf8.RuneCountInString function.

We count the number of bytes and runes of the msg string.

There are five runes and eight characters. This means that we have one rune which contains four bytes.

Go byte read file

Many built-in I/O functions in Go return a slice of bytes.

We read this text file.

The ioutil.ReadFile reads the specified file and returns its contents as a slice of bytes.

Go byte read binary file

In the following example, we read a binary file and output it in a hexadecimal view.

The hex.Dump function returns a string that contains a hex dump of the given data. The format of the hex dump matches the output of hexdump -C Unix command.

Go escaped bytes

Arbitrary character values can be encoded with backslash escapes and used in string or rune literals. Go supports a common format in which a byte is represented as \x followed by two hexadecimal values.

In the code example we print six emoji characters. These emojis are are specified as escaped bytes.

Go bytes functions

The bytes package contains functions for manipulation of byte slices.

In the code example, we use Contains , Equal , and Fields functions.

With Contains we check if data2 slice is a subslice of data1 .

With Equal we check if two slices are the same length and contain the same bytes.

The Fields function splits a byte slice into subslices removing any space characters, including newlines.

In the next example, we use another three functions.

The example joins byte slices with Join , repeats a byte slice with Repeat , and trims byte slices of the specified byte with Trim .

Go bytes.Buffer

The bytes.Buffer is a variable-sized buffer of bytes with Read and Write methods.

We build a bytes.Buffer with Write , WriteByte , WriteString , WriteByte , and WriteRune methods.

In this article we have worked with bytes in Golang.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Go tutorials .

GO Bytes to String Conversion Best Practices [5 Methods]

Deepak Prasad

September 29, 2023

Byte slices ( []byte ) and strings are two of the basic data structures in Go programming language used to represent both text and binary data. These can be sequences of characters, but differ in a number of aspects such as mutability, usage and internal representation. In Go, a string is an immutable sequence of bytes with a definite length which makes it safe to share these objects among multiple goroutines concurrently. Conversely, a slice of bytes is capable of being modified and refers to an array containing those bytes. Because of this, an operation to convert or bridge between the two types has become commonplace for input-output tasks, file handling or network communications.

Different Methods for GO Bytes to String conversion

  • Direct conversion using type casting.
  • Use the fmt.Sprintf function for string formatting.
  • Utilizing the strings.Builder for efficient concatenation in loops.
  • Applying the strconv package for conversion with numeric interpretation.
  • The bytes.Buffer helps you convert and manipulate byte slices.
  • Reads bytes from files into strings straight from io/ioutil packages (note that ioutil has been deprecated since Go 1.16, and similar functionality is now available in os and io ).
  • For go versions before 1.16, use io/ioutil package’s ReadAll function combined with a reader interface then cast.
  • Using os package functions read into a byte slice from files or other sources of input before converting

1. Direct conversion using type casting

One of the most basic and simple methods in which you can convert a byte slice ( []byte ) to a string in Go is direct conversion using type casting. What this method does is use Go's type conversion syntax to transfer data from one type to another, which will be on our end []byte to string. If you aren't aware, strings in Go are a read-only slice of bytes. That being known, there's no need for complex processes or external library functions when converting from []byte aka the byte slice that we're given. All we need to do is instruct the compiler directly by treating it as a string. This operation isn't only very efficient because it doesn't copy any bytes but instead creates a header that points to the same underlying byte array.

Examples of Direct Type Conversion :

Basic Conversion :

Here, we've got a straightforward example where a byte slice b representing the word "Hello" is converted directly to a string s .

Numeric Byte Values :

This example uses the ASCII values for the characters. When converted, it still produces the word "Hello" as a string.

Non-ASCII Characters :

Go's string and byte slice types support UTF-8 encoding natively. Here, the byte slice represents the Chinese phrase "你好" (Hello).

Empty Byte Slice :

Even when dealing with empty byte slices, direct conversion results in an empty string without any issues.

2. Using fmt.Sprintf

The Go standard library has a versatile format string function , fmt.Sprintf . It not only converts different data types into string but also formats them in accordance with specific patterns. In terms of converting byte slices ( []byte ) to strings, fmt.Sprintf offers an option for doing so along with additional formatting options if required. On the other hand, while fmt.Sprintf is not the most direct way to convert bytes to a string because it incurs the overhead of handling a format string, it proves useful when you want to either include that byte slice within a larger string or get more out of the byte data in question by giving it particular forms of formatting.

If you want to convert a byte slice into a string using fmt.Sprintf then you can apply %s format verb which implies that argument should be formatted as a string. Here are some examples of Converting Byte Slices to Strings using fmt.Sprintf :

In this example, fmt.Sprintf is employed to convert the byte slice b to a string. The format verb %s is used to represent the byte slice as a string.

With Additional Formatting :

Here, we not only perform the go bytes to string conversion but also embed the resulting string within a larger formatted string.

Conversion Alongside Other Data Types :

This example showcases the power of fmt.Sprintf to handle multiple data types concurrently , integrating the byte-to-string conversion seamlessly within a broader context.

Hexadecimal Representation :

Using the %x verb, we can represent the byte slice in its hexadecimal form, illustrating fmt.Sprintf 's flexibility beyond mere string representation.

3. Using bytes.Buffer Type

The bytes.Buffer type within the Go library is a variable-sized, very perplexing buffer of bytes with read and write methods. This type is part of the bytes package , and it is commonly used for reading from and writing to buffers. The bytes.Buffer in Go is used for efficient manipulation and conversion of byte slices.

Examples of Conversion Using the bytes.Buffer Type :

Here, we initiate a Buffer , write our byte slice b to it, and then effortlessly convert it into a string using the String() method.

Concatenating Multiple Byte Slices :

With Buffer , concatenating multiple byte slices becomes a breeze. This approach is not only intuitive but also efficient, especially when dealing with multiple byte slices.

Applying Transformations Before Conversion :

One of the beauties of Buffer is its seamless integration with other packages, allowing for transformations, like converting to lowercase, post-conversion.

Efficient Handling of Large Byte Slices :

Buffer type is a memory efficient way to convert a bunch of bytes into a string, it just works by minimizing allocations during operations.

Honestly direct conversion and fmt.Sprintf can do the job for basic use cases. But there are scenarios where the Buffer approach can be advantageous:

  • Large Data Handling : If you're working with vast amounts of data, the Buffer type will make sure your memory usage stays efficient
  • Multiple Concatenations:  Let's say you need to add or combine multiple byte slices, Buffer performs significantly better than simple slice appending.
  • Flexibility : It plays well with other Go packages like strings, allowing you to execute many different operations beyond just converting things.

4. Using unsafe

The unsafe package is a unique one within the vast realm of packages that Go offers. While other packages focus on more general, mundane tasks, unsafe says “screw that” and shows you Go’s memory representation and its type system. But if its name is asking for caution, it’s probably for good reason. Of the many things you can do with this package, one that stands out is how it handles byte to string conversion. But as versatile as it may be, its risks are equally noteworthy.

General Summary: The Go package called unsafe is a double-edged sword. Although it gives developers direct access to manipulating memory and converting types at a low level, it ditches the safety mechanism in place by default in Go's type system. This means applications built using this package might run into unexpected behaviors or vulnerabilities if misused.

Examples of Conversion Using the unsafe Package :

Basic Unsafe Conversion :

Here, we directly manipulate memory pointers to cast a byte slice to a string. It's quick and allocates no additional memory, but it's, well, unsafe.

Pitfalls of Using Unsafe : Suppose you modify the original byte slice after converting it using unsafe :

In this example, we saw just how closely tied the byte slice and string are when converted with unsafe . Changing one will affect the other — something you wouldn’t expect at first glance and could pose dangers in some situations.

Possible Pitfalls : You don’t need me to tell you that bypassing type safety opens up a world of opportunities for optimizations. However, these opportunities come with risks:

  • Memory Safety : Go’s robust type system goes a long way in preventing common programming mistakes. Going around it leaves open entirely new ones related to memory management.
  • Maintenance Trouble : Code that uses this package can become harder to maintain and evolve as changes are made to the language or compiler itself.
  • Data Integrity : If there’s anything these examples have shown us, it’s that data integrity can be compromised when sharing references between unsafe variables that stakeholders may modify incorrectly.

5. Using strings.Builder Method

The strings.Builder type within Go's standard library was designed for efficiently building strings through data appending, including but not limited to: bytes or strings themselves. Strings.Builder provides a way for developers like yourself to construct strings more efficiently than with concatenation. In scenarios where multiple appends are performed, it minimizes memory copying and allocation which makes it faster than other methods.

Although strings.Builder has been crafted primarily for string construction rather than converting byte slices; That doesn’t mean you can’t use it for that purpose — especially if many appends will be performed before doing so

Examples of Conversion Using the strings.Builder Method :

Basic Conversion using strings.Builder :

Here, we initiate a strings.Builder , write our byte slice to it, and then convert it to a string.

Appending Multiple Byte Slices :

Using strings.Builder makes adding multiple byte slices together before completing the string switch so much easier.

Comparing strings.Builder with bytes.Buffer : Strings.Builder and bytes.Buffer may seem to do similar things but they have their distinctions:

  • Purpose Specificity :  bytes.Buffer is considered a more general-purpose buffer because it holds both bytes and strings. On the other hand, string builders only work with string building, this means that code using them is much clearer in its intent.
  • Performance : For tasks that only deal with building strings, strings.Builder might be faster due to it being stripped of additional functionality provided by bytes.Buffer .
  • Methods Availability:   bytes.Buffer has a bigger selection of methods for more flexible byte-based operations while string builders have minimalistic APIs.

In the course of learning how to convert byte slices to strings in Go, we have seen that several methods can be used with their own unique characteristics and appropriate applications. As earlier stated, a variety of tools are out there for Go programmers:

  • Direct Type Conversion : A simple and effective technique which is suitable for almost all common situations.
  • Using fmt.Sprintf : This approach is flexible giving more than just conversion and especially if formatting is important.
  • The bytes.Buffer Type : It’s perfect when manipulating or concatenating byte slices needs to be done efficiently.
  • The Risky unsafe Package : The best specialist tool ever known which one should not touch unless there is a compelling performance need, even then with great care.
  • The strings.Builder Method : This method is specialized and optimized for string building hence it finds use in applications where string manipulation dominates.

All in all, the “go bytes to string” problem reflects the richness of Go as a language. However, every single method has its peculiarities such that it might be judged pragmatically given certain aspects including speed, safety and readability.

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

Save my name and email in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

Exam certifications.

Certified Kubernetes Application Developer (CKAD)

CompTIA PenTest+ (PT0-002)

Red Hat EX407 (Ansible)

Hacker Rank Python

Privacy Policy

IMAGES

  1. 深入golang -- slice

    golang byte slice assignment

  2. Golang Tutorial: Slice size vs. capability

    golang byte slice assignment

  3. Golang Slice Example

    golang byte slice assignment

  4. Golang Slice

    golang byte slice assignment

  5. Slices in Golang

    golang byte slice assignment

  6. Golang Tutorial #13

    golang byte slice assignment

VIDEO

  1. Golang. Slices (Слайсы)

  2. Golang Slice

  3. Tutorial # 17 Assignment Operators

  4. Dream Byte ....AGR101M Assignment...LPU#lpu

  5. Java Basics Tutorial

  6. Golang backend assignment Demo

COMMENTS

  1. Go Slices: usage and internals

    The slice type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays. An array type definition specifies a length and an element type. For example, the type [4]int represents an array of four integers. An array's size is fixed; its length is part of its type ( [4]int and [5]int are ...

  2. Understanding slice assignment in Go

    And then, "newSlice" was kind of cloned back to "slice". Yeah, Go does feel strange about this thing, as not also the content is copied, but "slice" now has the same capacity as "newSlice". But it is not like a "pointer assignment" in C, as we still have two different slice instances and what happens to one doesn't affect the other.

  3. go

    The built-in copy function only copies to a slice, from a slice.; Arrays are "the underlying data", while slices are "a viewport into underlying data". Using [:] makes an array qualify as a slice.; A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).; If the string is too long, copy will only copy the part of ...

  4. go

    8. Slices in go are a fancy structure that sits on top of an array. In your example: s := []int{2, 3, 5, 7, 11, 13} Creates an array with the contents: 2, 3, 5, 7, 11, 13 and the slice s points to that array and it's as long as the array itself. When slicing s = s[:0] this creates a new slice with length 0 on the same array.

  5. Bits, Bytes, and Byte Slices in Go

    Taking the information from above, we could create a byte slice that represents the word "Go": bs := []byte{71, 111} fmt.Printf("%s", bs) // Output: Go. You may notice the %s used here. This ...

  6. bytes package

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

  7. Golang Bytes: Slices and Methods

    Bytes. A byte is an 8-bit unsigned int. In Go we often use byte slices. And the "bytes" package provides helper methods for byte slices (similar to strings). We use methods, like append (), to build byte slices. We can specify them with string literals. Methods like bytes.Index help us test and change bytes. Byte slices.

  8. Go Wiki: SliceTricks

    Go Wiki: SliceTricks. Move to front, or prepend if not present, in place if possible. Since the introduction of the append built-in, most of the functionality of the container/vector package, which was removed in Go 1, can be replicated using append and copy. Since the introduction of generics, generic implementations of several of these ...

  9. bytes

    func (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. func (*Buffer) Read ¶

  10. Go slice

    A slice can grow and shrink within the bounds of the underlying array. A slice does not store any data, it just describes a section of the array. Go declare slice var s []T We declare a slice having type T. The slice is declared just like an array except that we do not specify any size in the brackets []. $ go version go version go1.22.2 linux ...

  11. Golang bytes

    Golang "bytes" package. The "bytes" package implements many useful functions that can be used to manipulate byte slices. It also contains a type Buffer which is an important struct that we will be exploring later on. Here are some of the most useful functions that can be used with byte slices. 1. Compare byte slices

  12. Understanding Golang Slice: A Comprehensive Guide

    This makes slice operations as efficient as regular array operations. However, it also means that if you modify the elements of a slice, it will affect the original array and all other slices that refer to it. In conclusion, slices in GoLang are an incredibly powerful feature that allow you to work with dynamic sequences of elements.

  13. Slices in Golang

    Creating slices in Golang. Noe, we will see how we can create slices for our usage. There are quite a few ways we can create a slice. 1. Using slice literal syntax. Slice literal is the initialization syntax of a slice. Below is an example of using slice literal syntax to create a slice. 2. Creating slices from an array.

  14. Go byte

    A byte in Go is an unsigned 8-bit integer. It has type uint8. A byte has a limit of 0 - 255 in numerical range. It can represent an ASCII character. Go uses rune, which has type int32, to deal with multibyte characters. The bytes package implements functions for the manipulation of byte slices. It is similar to the strings package.

  15. Efficient Slice Concatenation in Go and A New Function in Go1.22

    The upcoming Go 1.22 release includes a 'Concat' function for a more streamlined slice concatenation. a := []int{1, 2, 3} b := []int{4, 5, 6} c := slices.Concat(nil, a, b) This method is not only more succinct but also optimizes memory allocation and copying operations, suitable for high-performance scenarios.

  16. GO Bytes to String Conversion Best Practices [5 Methods]

    1. Direct conversion using type casting. One of the most basic and simple methods in which you can convert a byte slice ([]byte) to a string in Go is direct conversion using type casting.What this method does is use Go's type conversion syntax to transfer data from one type to another, which will be on our end []byte to string. If you aren't aware, strings in Go are a read-only slice of bytes.

  17. How to efficiently convert a string to a byte slice, including the

    Allocate a slice of the desired length. Copy the string to the slice. s := "abc". my_slice := make([]byte, len(s)+1) copy(my_slice, s) There's no need to set the last element to zero because make returns a slice with all elements set to zero. edited Jun 13, 2018 at 12:50. answered Jun 13, 2018 at 3:23.

  18. Golang: Deep and Shallow Copy a Slice

    copy built-in function. copy function copies elements from a source (src) slice into a destination (dst) slice. func copy(dst, src []Type) int. Create a new empty slice with the same size of the src and then copy all the elements of the src to the empty slice. Using the copy function, src and dst slices have different backing arrays.

  19. How to convert from []byte to int in Go Programming

    binary.Read in encoding/binary provides mechanisms to convert byte arrays to datatypes.. Note that Network Byte Order is BigEndian, so in this case, you'll want to specify binary.BigEndian.. package main import ( "bytes" "encoding/binary" "fmt" ) func main() { var myInt int b := []byte{0x18, 0x2d} // This could also be a stream buf := bytes.NewReader(b) err := binary.Read(buf, binary.BigEndian ...