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