3

Maybe a stupid question, but if I have some arbitrary binary data, can I cast it to string and back to byte array without corrupting it?

Is []byte(string(byte_array)) always the same as byte_array?

2
  • 3
    Wastes memory on copies so it makes GC happen sooner, but provided you don't actually exhaust system RAM by copying something the size of all your free RAM or similar, yes, result is byte-identical.
    – twotwotwo
    Sep 23, 2015 at 0:14
  • 6
    This blog post may be helpful and in particular notes that strings can contain things other than UTF-8 text.
    – twotwotwo
    Sep 23, 2015 at 0:20

1 Answer 1

3

The expression []byte(string(byte_slice)) evaluates to a slice with the same length and contents as byte_slice. The capacity of the two slices may be different.

Although some language features assume that strings contain valid UTF-8 encoded text, a string can contain arbitrary bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.