-2

I have encountered a situation that I do not understand.

    a := "hello"
    fmt.Printf("%v %T\n",a[0],a[0])

This gives 104 uint8.

    for _,v := range a {
        fmt.Printf("%v %T\n",v,v)
    }

This gives 104 int32 for the first iteration. I don't understand why their types are not same. First one is byte, second one is rune. I expect both to be byte.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Shadovx
  • 115
  • 1
  • 8
  • `a` is a string and not a slice of byte. And that's how `for` loops over strings work. If there wasn't a special rule for strings you couldn't range over strings at all as these are neither arrays, slices nor channels. – Volker Mar 23 '20 at 05:59

1 Answers1

3

This might explain it:

https://blog.golang.org/strings

In short: if a is a string, a[i] is a byte, but here, r is a rune:

for _,r:=range a {
...
}

When you range over a string, you range over the runes of that string. To range over the bytes of a string, use:

for i:=0;i<len(a);i++ {
   // Here, a[i] is byte
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59