4

What's the best way to convert from []uint8 to string?

I'm using http://github.com/confluentinc/confluent-kafka-go/kafka

To read events from kafka. But it does not return plain string event. It returns event with type []uint8. How can I convert this event from []uint8 to string?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Le D. Thang
  • 613
  • 1
  • 7
  • 11

1 Answers1

15

byte is an alias for uint8, which means that a slice of uint8) (aka []uint8) is also a slice of byte (aka []byte).

And byte slices and strings are directly convertible, due to the fact that strings are backed by byte slices:

myByteSlice := []byte{ ... }     // same as myByteSlice := []uint8{ ... }
myString := string(myByteSlice)  // myString is a string representation of the byte slice
myOtherSlice := []byte(myString) // Converted back to byte slice
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189