Joe
Joe

Reputation: 47729

Go range over uint8 slice?

EDIT This was due to a stupid error in my part, but the question is worth keeping around in case someone else does this.

I would hope that this works:

var xs []uint8
var x uint8
for x = range xs {

}

But I get the error:

cannot assign type int to x (type uint8) in range

i.e. (as I understand it) the range, even though it is operating on a slice of uint8, is trying to use int as the iterated value.

I have looked through the language spec, the relevant bit:

Range expression                          1st value          2nd value (if 2nd variable is present)

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E

so I would expect it to be E the 'parameterised type'*, in this case uint8 not int.

Have I grasped onto the wrong end of the stick? Is there a bit of documentation that I missed? Or can I really not iterate over a uint8 slice with a uint8 variable?

*I know it's not really a generic parameterised type.

Upvotes: 4

Views: 2039

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

range returns an index into a collection and possibly the value at that position:

range keyword The range keyword allows you to iterate over items of a list like an array or a map. For understanding it, you could translate the range keyword to for each index of. When used with arrays and slices, it returns the integer index of the item. (tutorial)

sample code:

package main

import "fmt"

func main() {
    var xs []uint8 = []uint8{255, 254, 253}
    var idx int
    var ui8 uint8
    for idx, ui8 = range xs {
        fmt.Println(idx, ui8)
    }
}

output:

0 255
1 254
2 253

P.S.:

Perhaps a look at Javascript will make Go's approach less strange:

% a = [255, 254, 253]
255,254,253
% for (x in a) { print(x, " ", a[x]); }
0 255
1 254
2 253

Upvotes: 6

Related Questions