2

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?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
Le D. Thang
  • 573
  • 1
  • 5
  • 11
  • 1
    Look here: [enter link description here](https://stackoverflow.com/questions/19223277/how-to-convert-uint8-to-string/21520223) – Daniel Jun 18 '19 at 04:53
  • 2
    https://tour.golang.org/basics/13 – Peter Jun 18 '19 at 05:17
  • 1
    Simply `string(uint8slice)`. See [How to convert \[\]int8 to string](https://stackoverflow.com/questions/28848187/how-to-convert-int8-to-string/28848879?r=SearchResults#28848879). – icza Jun 18 '19 at 06:22
  • 1
    Note that's a slice, not an array. – Flimzy Jun 18 '19 at 09:16

1 Answers1

12

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
Flimzy
  • 68,325
  • 15
  • 126
  • 165