HiveBrain v1.2.0
Get Started
← Back to all entries
principlegoMajor

When to use []byte or string in Go?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringbyteusewhen

Problem

Frequently in writing Go applications, I find myself with the choice to use []byte or string. Apart from the obvious mutability of []byte, how do I decide which one to use?

I have several use cases for examples:

  • A function returns a new []byte. Since the slice capacity is fixed, what reason is there to not return a string?



  • []byte are not printed as nicely as string by default, so I often find myself casting to string for logging purposes. Should it always have been a string?



  • When prepending []byte, a new underlying array is always created. If the data to prepend is constant, why should this not be a string?

Solution

My advice would be to use string by default when you're working with text. But use []byte instead if one of the following conditions applies:

-
The mutability of a []byte will significantly reduce the number of allocations needed.

-
You are dealing with an API that uses []byte, and avoiding a conversion to string will simplify your code.

Context

Stack Overflow Q#10826651, score: 54

Revisions (0)

No revisions yet.