0

I'm trying to loop over slice of user defined types (in example below these are aliased int), but range produces values of type int, instead of MyInt as I would expect. Casting inside 'if' helps for sure, but I would like to understand why range does not produces values of type MyInt.

package main

import (
    "fmt"
)

type MyInt int

const (
    MYINT00 MyInt = iota
    MYINT01
)

func main() {
    var myInt02 MyInt = 2
    myInts := []MyInt{MYINT00, MYINT01}
    for i := range myInts {
        if i == myInt02 {
            fmt.Println("same")
        }
    }
}

Playground: https://play.golang.org/p/nb77pvTMdkW

Error:

prog.go:18:8: invalid operation: i == myInt02 (mismatched types int and MyInt)

Then I thought that problem can be related to consts and iota, so I used variables declared in function - didn't change anything.

https://play.golang.org/p/0fVRhBtvlOL https://play.golang.org/p/pioDSU4oJdP

I haven't found any info in Effective Go/other questions. If anybody has some input on that, please share!

peterSO
  • 158,998
  • 31
  • 281
  • 276
cezkuj
  • 19
  • 2

1 Answers1

4

The Go Programming Language Specification

For statements with range clause

Range expression                          1st value          2nd value

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

i is the range index, an int, not the range value.

For example, fixing your code to use the range value,

package main

import (
    "fmt"
)

type MyInt int

const (
    MYINT00 MyInt = iota
    MYINT01
)

func main() {
    var myInt02 MyInt = 2
    myInts := []MyInt{MYINT00, MYINT01}
    for _, v := range myInts {
        if v == myInt02 {
            fmt.Println("same")
        }
    }
}
peterSO
  • 158,998
  • 31
  • 281
  • 276