converting byte to string

Duration: 3 mins

byte and []byte to string

Instructor

Matt Boyle

Share with a friend!

Transcript

You may have come across bytes in Go. Sometimes you end up working with bytes or slices of bytes where maybe you wouldn't really expect to. You'd be expecting to be working with a string. And it does have a few quirks because bytes are effectively an alias for Uint8. So let's figure out how we can move from a world where we have something that's a byte to treating it like a string.

So let's say we have something like this. If we print this, we maybe didn't get what we expected. So let's convert it to a string now. And the nice thing about this is you can actually just directly cast here and this does work. Okay, so that gives us what we wanted. So that was a really easy way to move between bytes and strings.

So let's say we had something a little bit more complicated. Let's say we have this byte slice. Now the nice thing is you can still just do this. Hey look, it says "v" here. But here's some strange gotchas to be aware of. Let's say we have something like this, which is valid, and we want to print that. This has had the opposite effect of what we wanted previously.

So therefore we do have to convert this. And to do that we can use the string conversion package. Okay, and that's what we wanted. You also may have something like this. This is printed a weird thing because this is invalid UTF-8.

Okay. So this might leave you the question, why do people use slices of bytes instead of strings in Go? There's a few reasons. Firstly, in Go strings are immutable, which is great for safety but it is limiting. A slice of bytes is mutable, which means we can change it, which that makes it versatile.

For binary data, strings are UTF-8 encoded, but slices of bytes handle raw bytes, which is perfect for binary protocols such as things like gRPC. Finally, building strings repeatedly is costly due to the fact that they are immutable, whereas if you use a slice of bytes you can use a buffer and it's really fast, which leads to fewer allocations and better performance.

And then finally, converting from a slice of bytes to a string can be done really easily and it can't be done the other way without a use of the copy function. So generally, the reason for using slice of bytes a lot is just for efficiency reasons and the fact that it's so easy to change it into a string as we've seen here, there's just not really many downsides to doing so.