循环遍历字符串返回int32

sha*_*rni 0 loops range go

int32与其他语言不同,为什么在字符串中返回值而不是原始字符?

例如:

func main() {

    var s string
    s = "Hello"
    for _, v := range s {
        fmt.Println(v)
    }

}
Run Code Online (Sandbox Code Playgroud)

返回:

72
101
108
108
111
Run Code Online (Sandbox Code Playgroud)

我们应该使用如下所示的转换来获取原始字符吗?

func main() {

    var s string
    s = "Hello"
    for _, v := range s {
        fmt.Println(string(v))
    }

}
Run Code Online (Sandbox Code Playgroud)

pet*_*rSO 7

Go编程语言规范

对于陈述

对于带有范围子句的语句

为一个字符串值,在串中的Unicode码点"范围"的条款进行迭代开始于字节索引0.连续迭代,该指数值将是连续的UTF-8编码的码点的第一个字节的索引字符串和rune类型的第二个值将是相应代码点的值.如果迭代遇到无效的UTF-8序列,该第二值将是0xFFFD,Unicode替换字符,并在下一次迭代将字符串中推进一个字节.


在Go中,字符是Unicode代码点,Go类型rune(别名int32).Go string用于以UTF-8编码形式存储Unicode代码点.


Go编程语言规范

转换

转换为字符串类型的转换

将有符号或无符号整数值转换为字符串类型会生成包含整数的UTF-8表示形式的字符串.超出有效Unicode代码点范围的值将转换为"\ uFFFD".

string('a')       // "a"
string(-1)        // "\ufffd" == "\xef\xbf\xbd"
string(0xf8)      // "\u00f8" == "ø" == "\xc3\xb8"
type MyString string
MyString(0x65e5)  // "\u65e5" == "?" == "\xe6\x97\xa5"
Run Code Online (Sandbox Code Playgroud)

例如,

package main

import (
    "fmt"
)

func main() {
    helloworld := "Hello, ??"
    fmt.Println(helloworld)
    for i, r := range helloworld {
        fmt.Println(i, r, string(r))
    }
}
Run Code Online (Sandbox Code Playgroud)

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

输出:

Hello, ??
0 72 H
1 101 e
2 108 l
3 108 l
4 111 o
5 44 ,
6 32  
7 19990 ?
10 30028 ?
Run Code Online (Sandbox Code Playgroud)

参考文献:

Go Blog:Go中的字符串,字节,符文和字符

Unicode联盟