Golang Byte Array to String In Multiple ...

Golang Byte Array to String In Multiple Ways

Oct 15, 2021

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 byte array to string.

Golang have string function which can easily convert your byte 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 byte 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. Using bytes package to convert byte 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

so these are the possible ways to convert array of bytes to string, if you think this article is useful don't forget to leave a comment

Checkout more : https://kdsingh4.blogspot.com/

Full Code:

Enjoy this post?

Buy kdsingh a book