Putting int8 in an array of bytes

I have the following byte array:

buf := make([]byte, 1) var value int8 value = 45 buf[0] = value // cannot use type int8 as type []byte in assignment 

And when I want to put the char value in an array of bytes, I get the error message I cannot use type int8 as type []byte in assignment . What's wrong? How to do it?

+5
source share
2 answers

The problem you are facing is that although int8 and byte roughly equivalent, they are not the same. Go is a little more strict than, say, PHP (which is not so difficult). You can get around this by explicitly specifying a value on byte :

 buf := make([]byte, 1) var value int8 value = 45 buf[0] = byte(value) // cast int8 to byte 
+2
source

Try the following:

 buf := make([]byte, 1) var value int8 value = 45 buf[0] = byte(value) 

UPDATE : deduced a code converting negative numbers to positive. It looks like byte(...) already doing this conversion in current versions of Go.

+1
source

All Articles