go 语言 fmt对string中零值的处理

fmt格式化含有0值的string时,是如何显示的

func main() {
	buf := make([]byte, 10)
	buf[8] = 'A'
	copy(buf, []byte("hello"))
	fmt.Printf("cap(%d),len(%d)\n", cap(buf), len(buf))
	fmt.Println("buf:", buf)
	fmt.Printf("buf:%q\n", buf)
	fmt.Println("buf:", string(buf))

	str := string(buf)
	str = str + " world"
	fmt.Println(len(str)) // => 16
	fmt.Println(str)      // => helloA world
}

/* output
cap(10),len(10)
buf: [104 101 108 108 111 0 0 0 65 0]
buf:"hello\x00\x00\x00A\x00"
buf: helloA
16
helloA world
*/

1. 使用fmt打印string(buf)虽然显示为helloA,看上去字符数变少了,只有6个(0值没有显示,其ascii码是不可打印码),但底层数据没变,依然是[104 101 108 108 111 0 0 0 65 0]

2. 格式化参数%q直接对0值进行了输出hello\x00\x00\x00A\x00,它打印了string中的每一个字节,包括不可打印的字节

3. str + " world"的长度为16,也证明了str中的0值没有被去除(10 + 6 = 16)

4.使用fmt查看数据”长什么样子”有时候是不准确的