Just thought I'd run this one by you...

I used to often forget to specify the 2nd variable in a for-range:

    sum := ""
    for v := range []string{"1", "2", "3"} {
        sum += v
    }

luckilly (or because Go is so good at type safety) this generates the error:

  invalid operation: sum += v (mismatched types string and int)

I used to do this quite a bit which lead (when using an int slice) to one 
(maybe more that I haven't found yet :) bugs.  But for someone coming from 
a language with a for-range statement (like Python) it seems this type of 
bug is even more common:

    sum := 0
    for v := range []int{1, 2, 3} {
        sum += v // no error as they're both int
    }

Ideally you write tests to catch these sorts of things, but even with 100% 
coverage poor tests may not reveal the bug.  Then, if you're lucky, you get 
unexpected results or it could leave a nasty bug lurking in some 
rarely-executed piece of code.

A small fix to the language would avoid this problem.  If for-range indices 
had a different type then the above code could produce an error like.

  invalid operation: sum += v (mismatched types int and *for range index*)
  
The name of the new type could be something like *intforrangeindex*. 
 Perhaps something shorter, like *intindex*, if searching existing (Go 1) 
code reveals no potential conflicts, which I suspect it wouldn't.

BTW My gut was that *intindex *should be a signed int type but maybe 
unsigned would not be a problem.

This would be a proposal for Go 2 as it would not be backward compatible. 
 However, existing code could be easily converted (go fix ?) by just adding 
a type cast.  For example, if the above code was actually intended it could 
be written as:

    sum := 0
    for v := range []int{1, 2, 3} {
        sum += int(v)
    }

I think this is a small but worthwhile addition to type safety.

Note that go vet does not currently detect this problem but maybe it 
should.  A language change is better though, since not all code is vetted.

I was also thinking that *intindex* could be a hidden internal type but of 
course you can declare a loop index like this:

    var i int // type would change to intindex in Go 2
    for i = range []int{1, 2, 3} {
        sum += i
    }

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/e2609110-938a-4f1f-9f9e-dc05497dff37n%40googlegroups.com.

Reply via email to