user99999
user99999

Reputation: 2024

Putting int8 into byte array

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?

Upvotes: 7

Views: 8473

Answers (2)

user94559
user94559

Reputation: 60143

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.

Upvotes: 1

Ross McFarlane
Ross McFarlane

Reputation: 4254

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

Upvotes: 3

Related Questions