如下代码:

package main

import "fmt"

func main() {
    str := "s"
    for i, v := range str {
        fmt.Printf("type of s[%v]: %T\n", i, str[i])
        fmt.Printf("type of v: %T\n", v)
    }
}

产量:
type of s[0]: uint8
type of v: int32

在大多数语言中,字符串由带符号或无符号的8位字符组成。为什么用v而不是int32代替uint8

最佳答案



没有不一致的地方。

在Go中,Unicode代码点runeint32的别名。

Go不是限制于ASCII字符集的旧语言。像大多数[所有?]现代语言一样,Go使用Unicode。

例如,

package main

import "fmt"

func main() {
    helloworld := "Hello, 世界"
    fmt.Println(helloworld)
    for i, r := range helloworld {
        fmt.Println(i, r, string(r))
    }
}

游乐场:https://play.golang.org/p/Q_iEzdlGxLu

输出:
Hello, 世界
0 72 H
1 101 e
2 108 l
3 108 l
4 111 o
5 44 ,
6 32
7 19990 世
10 30028 界

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

The Unicode Consortium

09-04 05:01
查看更多