Thursday 7 October 2021

Golang Bytes of Array to String

In this article we are going to explore about the all possible ways to convert array of bytes to string in golang. So let's Start

1. Using string() function to convert bytes of array to string.

Golang have string function which can easily convert your bytes of array into string and this method is my favorite because it's easy to use without loading any other package.
Note: string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.

OUTPUT : GOLANG



2. Using fmt.Sprintf() function to convert bytes of array to string.

This is a another way to convert bytes of array to string. The Sprintf() function is a little bit slow but lot of people uses this to convert bytes of array to string.
Note: Sprintf formats according to a format specifier and returns the resulting string

OUTPUT : GOLANG



3. Usign bytes package to convert bytes of array to string.

We can use the bytes package NewBuffer() function to create new Buffer and then use the String() method to get the string output.
Note: 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.
Note 2: String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "".
To build strings more efficiently, see the strings.Builder type.

OUTPUT : GOLANG

Labels:

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home