Go 语言中的 string

内部表示

Go 语言的 string 是不可变的字节序列,是将文字按照 UTF-8 编码标准编码之后的字节序列。

demo

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	s := "hello, 世界"
	for i := 0; i < len(s); {
		r, size := utf8.DecodeRuneInString(s[i:])
		fmt.Printf("%d\t%c\n", i, r)
		i += size
	}
	// range loop decode a UTF-8-encoded string
	for i, r := range s {
		fmt.Printf("%d\t%c\n", i, r)
	}
	for i := 0; i < len(s); i++ {
		fmt.Printf("%d\t%c\n", i, s[i])
	}
}
0	h
1	e
2	l
3	l
4	o
5	,
6
7	世
10	界
0	h
1	e
2	l
3	l
4	o
5	,
6
7	世
10	界
0	h
1	e
2	l
3	l
4	o
5	,
6
7	ä
8	¸
9	–
10	ç
11	•
12	Œ