Why am I getting different types in strings?

47 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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
}