func TestString(t *testing.T) { var s string t.Log(s) //初始化爲默認零值"" s = "hello" t.Log(len(s)) //s[1] = '3' //string是不可變的byte slice s = "\xE4\xB8\xA5" t.Log(s) t.Log(len(s)) //s = "中" //t.Log(len(s)) //c := []rune(s) //t.Log("rune size:", unsafe.Sizeof(c[0])) //t.Logf("中 unicode %x", c[0]) //t.Logf("中 utf8 %x", s) }
輸出git
=== RUN TestString --- PASS: TestString (0.00s) string_test.go:9: string_test.go:11: 5 string_test.go:14: 嚴 string_test.go:15: 3 PASS Process finished with exit code 0
注意:len獲取的string的byte個數,不是字符數github
字符 | 「中」 |
---|---|
Unicode | 0x4E2D |
UTF-8 | 0x4EB8AD |
string/[]byte | [0xE4,0xB8,0xAD] |
func TestStringToRune(t *testing.T) { s := "中華人民共和國" for _, c := range s { t.Logf("%[1]c %[1]d", c) } }
輸出golang
=== RUN TestStringToRune --- PASS: TestStringToRune (0.00s) string_test.go:28: 中 20013 string_test.go:28: 華 21326 string_test.go:28: 人 20154 string_test.go:28: 民 27665 string_test.go:28: 共 20849 string_test.go:28: 和 21644 string_test.go:28: 國 22269 PASS Process finished with exit code 0
func TestConv(t *testing.T) { s := strconv.Itoa(10) t.Log("str:" + s) if i,err:=strconv.Atoi("10");err==nil{ t.Log(10+ i) } }
=== RUN TestConv --- PASS: TestConv (0.00s) string_fun_test.go:20: str:10 string_fun_test.go:22: 20 PASS Process finished with exit code 0
示例代碼請訪問: https://github.com/wenjianzhang/golearningshell