string

string 简析

reflect.StringHeader
type StringHeader struct {
  Data uintptr
  Len  int
}
"你好"你\xe4\xbd\xa0好\xe5\xa5\xbd

这里我们运行下述代码

	s := []byte{0xe4, 0xbd, 0xa0}
	fmt.Printf("char is %s", string(s))
char is 你

虽然字符串并非切片,但是支持切片操作。对于同一字面量,不同的字符串变量指向相同的底层数组,这是因为字符串是只读的,为了节省内存,相同字面量的字符串通常对应于同一字符串常量。例如:

	s := "hello, world"
	s1 := "hello, world"
	s2 := "hello, world"[7:]
	fmt.Printf("%d \n", (*reflect.StringHeader)(unsafe.Pointer(&s)).Data) // 17598361
	fmt.Printf("%d \n", (*reflect.StringHeader)(unsafe.Pointer(&s1)).Data) // 17598361
	fmt.Printf("%d \n", (*reflect.StringHeader)(unsafe.Pointer(&s2)).Data) // 17598368
hello, worldhhello, worldw

迭代字符串

for rangerunerune
	for index, char := range "你好" {
		fmt.Printf("start at %d, Unicode = %U, char = %c\n", index, char, char)
	}

得到运行结果

start at 0, Unicode = U+4F60, char = 你
start at 3, Unicode = U+597D, char = 好

随机访问字符串

string
	s := "你好"
	fmt.Printf("s[%d] = %q, hex = %x, Unicode = %U", 1, s[1], s[1], s[1])

得到运行结果

s[1] = '½', hex = bd, Unicode = U+00BD
0xbdU+00BD½

到底什么是rune、字符和字节

byteuint8

字符:字符的概念比较模糊,在Unicode中通常用code point来表示。在我的理解里,是一种信息单元(例如一个符号、字母等)

int32

总结

[]rune

参考