principlegoMajor
When to use []byte or string in Go?
Viewed 0 times
stringbyteusewhen
Problem
Frequently in writing Go applications, I find myself with the choice to use
I have several use cases for examples:
[]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?
[]byteare not printed as nicely asstringby default, so I often find myself casting tostringfor logging purposes. Should it always have been astring?
- When prepending
[]byte, a new underlying array is always created. If the data to prepend is constant, why should this not be astring?
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.
-
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.