github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch1/11_string_test.go (about) 1 package ch1 2 3 import ( 4 "testing" 5 "unsafe" 6 ) 7 8 func TestString(t *testing.T) { 9 var s string 10 t.Logf("s = %s\t\tlen = %d", s, len(s)) //初始化为默认零值“” 11 s = "hello" 12 t.Logf("s = %s\tlen = %d", s, len(s)) 13 14 //s[1] = '3' //string是不可变的byte slice 15 //t.Log(s, len(s)) 16 17 s = "\xE4\xB8\xA5" //可以存储任何二进制数据 18 t.Logf("s = %s\tlen = %d", s, len(s)) 19 20 s = "\xE4\xBA\xBB\xFF" 21 t.Logf("s = %s\tlen = %d", s, len(s)) 22 23 } 24 25 func TestRune(t *testing.T) { 26 // 1. Unicode是一种字符集(codepoint) 27 // 2. UTF8是unicode的存储实现(转换为字节序列的规则) 28 29 s := "中" 30 t.Logf("s = %s, byte数: %d", s, len(s)) //是byte数 31 c := []rune(s) 32 t.Log("rune size:", unsafe.Sizeof(c[0])) 33 t.Logf("中 unicode %x", c[0]) 34 t.Logf("中 UTF8 %x", s) 35 36 /* 37 38 字符 "中" 39 Unicode 0x4E2D 40 UTF-8 0xE4B8AD 41 string/[]byte [0xE4,0xB8,0xAD] 42 43 */ 44 } 45 46 func TestStringToRange(t *testing.T) { 47 s := "中华人民共和国" 48 for _, c := range s { 49 // [1] 代表第一个参数: c, [2] 代表第二个参数: 22 50 t.Logf("%[1]c %[1]x", c) 51 t.Logf("%[1]c %[1]d, %[2]d", c, 22) 52 } 53 }