On the go playground, this code
package main
import (
"fmt"
)
var a = []byte{ 0xff, 0xaa, 0x66, 0x33, 0x00 }
func main() {
for b := range a {
fmt.Printf("%T
", b)
}
}
prints
int
int
int
int
int
Why in the world wouldn't a slice of bytes give you bytes when you iterate through it (or at least uint8 or something)?
Here's the link to the playground: https://play.golang.org/p/V1uZZWWq-X.
for i := range thing
sets i
to indices into the thing (unlike Python or such). for i, b := range byteslice
would put the index in i
and byte in b
, and for _, b := range byteslice
would just put the byte in b
.
The spec on for statements lays out all the different special cases related to range
expressions (including strings, channels, and maps as well).
It's not the slice/bytes/strings/runes causing the problem. It's your use of range. You're expecting to be looking at the current item but you're actually looking at the integer that represents the current index on each iteration of the loop.
To be clear, if your loops form is; for i, v := range
then i
is an int representing the current index while v
is a block of temporary storage that the value at index i
is assigned to. If you want only the values then your loop would be; for _, v := range
. When you only have one identifier on the left it assigned the index, not the value.