在go中遍历字符串字符的最正确方法是什么

I am newbie at Go and I wish to iterate the characters of a string

package main

import (
    "fmt"
)

func main() {
    var a string = "abcd"
    for i, c := range a {
        fmt.Printf("%d %s
", i, c)
    }
}

I want the output to be

    0 a
    1 b
    2 c
    3 d

but it's not. What am I doing wrong?

Fix the go vet and package fmt format error messages (type rune is an alias for type int32):

10: Printf format %s has arg c of wrong type rune

0 %!s(int32=97)
1 %!s(int32=98)
2 %!s(int32=99)
3 %!s(int32=100)

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

A rune is a Unicode code point (character), not a string.

Use %c not%s. For example,

package main

import (
    "fmt"
)

func main() {
    var a string = "abcd"
    for i, c := range a {
        fmt.Printf("%d %c
", i, c)
    }
}

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

Output:

0 a
1 b
2 c
3 d

An example of type string UTF-8 variable-length encoding:

package main

import (
    "fmt"
)

func main() {
    var a string = "Greece Ελλάδα"
    for i, c := range a {
        fmt.Printf("%2d %c
", i, c)
    }
}

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

Output:

 0 G
 1 r
 2 e
 3 e
 4 c
 5 e
 6  
 7 Ε
 9 λ
11 λ
13 ά
15 δ
17 α

References:

Go package fmt documentation.

The Go Blog: Strings, bytes, runes and characters in Go.