7

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 a char value into the byte array I get the error that I cannot use type int8 as type []byte in assignment. What's wrong? How do I do this?

user99999
  • 1,994
  • 5
  • 24
  • 45
  • dont know much about `go` but have you either accidently made a array of an array? Or try casting int8 to byte first. – IAmGroot Jun 24 '16 at 09:56
  • Possible duplicate of [Convert an integer to a byte array](http://stackoverflow.com/questions/16888357/convert-an-integer-to-a-byte-array) – Mario Santini Jun 24 '16 at 10:06

2 Answers2

3

The issue you're having their is that although int8 and byte are roughly equivalent, they're not the same type. Go is a little stricter about this than, say, PHP (which isn't strict about much). You can get around this by explicitly casting the value to byte:

buf := make([]byte, 1)
var value int8
value = 45
buf[0] = byte(value) // cast int8 to byte
Ross McFarlane
  • 4,054
  • 4
  • 36
  • 52
  • 2
    Worth noting that `byte` is just an alias for `uint8` in Go. That means the major difference is that you're trying to store a signed value into an unsigned slot. Typecasting to `uint8`, or using a uint8 in the first place, works for this without needing a `byte` typecast. Example: https://play.golang.org/p/XzQ7eWOS16 – Kaedys Jun 24 '16 at 15:26
1

Try this:

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

UPDATE: Took out the code converting negative numbers to positive ones. It appears that byte(...) already does this conversion in current versions of Go.

user94559
  • 59,196
  • 6
  • 103
  • 103
  • 1
    No need this "tricky" conversion, a simple `byte(value)` gives the same result. – icza Jun 24 '16 at 11:45
  • It looks like you're right! I wonder if something changed here... I had found an older resource that expressed the need to convert to a positive number first. – user94559 Jun 24 '16 at 17:10
  • There was no change. Either the old source was incorrect, or maybe it related to another language? Or maybe that included constant expressions... – icza Jun 24 '16 at 17:40
  • @icza Amazingly, I think my source was you! :-) http://stackoverflow.com/questions/28848187/golang-convert-int8-to-string/28848879#28848879 – user94559 Jun 24 '16 at 19:46