DEV Community

fy
fy

Posted on

Golang - why is function return type always byte ([])?

Most of the packages in golang return response in byte ([]).

e.g if you do

exec.Command("ls").Output() or http.Get("http://example.com") or anything else, the response is in byte ([]).

whats the reasoning behind this?

Top comments (3)

Collapse
 
ajsharp profile image
Alex Sharp 🛠sharesecret.co

Byte arrays and strings have some key differences, the main one being byte arrays/slices are mutable, while strings are immutable. My guess is many places byte arrays are returned have to do with that, and the ability to efficiently change the size of the array without allocating new memory. So, if you're reading from a unix socket and you don't know how much data you're going to read (the case with both the examples above) it's probably faster to use a byte array rather than re-allocate a larger string every time you read more data from the socket.

Collapse
 
devdrake0 profile image
Si

Byte arrays and strings have some key differences

This could be misleading to people unfamiliar with Go. The underlying structure of strings are byte arrays, which is why you have to be careful when you loop over a string because it'll give you byte-by-byte not character-by-character.

My guess is many places byte arrays are returned have to do with that, and the ability to efficiently change the size of the array without allocating new memory.

Byte arrays are used because they can be unmarshalled, whereas strings cannot.

Collapse
 
victoravelar profile image
Victor Avelar

Hi Fayz, I am happy to see you are ramping up your go game. 😄