[go learning notes] 9. Strings in go language

Posted by syd on Fri, 20 Mar 2020 15:47:14 +0100

Character string

  • string is a data type, not a reference or pointer type
  • string is a read-only byte slice. The len function can get all the bytes
  • The byte array of string can hold any data
func TestString(t *testing.T) {
    var s string
    t.Log(s) //Initialize to default zero value ''
    s = "hello"
    t.Log(len(s))
    //s[1] = '3' //string is immutable byte slice
    s = "\xE4\xB8\xA5"
    t.Log(s)
    t.Log(len(s))
    //s = "medium"
    //t.Log(len(s))
    //c := []rune(s)
    //t.Log("rune size:", unsafe.Sizeof(c[0]))
    //t.Logf("Unicode% X in, C [0])
    //t.Logf("utf8% X", s)
}

output

=== RUN   TestString
--- PASS: TestString (0.00s)
    string_test.go:9: 
    string_test.go:11: 5
    string_test.go:14: strict
    string_test.go:15: 3
PASS

Process finished with exit code 0

Note: the number of byte s of string obtained by len, not the number of characters

Unicode UTF8

  • Unicode is a character set (code point)
  • UTF8 is a storage implementation of unicode (rules for converting to byte sequences)

Coding and storage

character "Zhong"
Unicode 0x4E2D
UTF-8 0x4EB8AD
string/[]byte [0xE4,0xB8,0xAD]

Common string functions

func TestStringToRune(t *testing.T) {
    s := "The People's Republic of China"
    for _, c := range s {
        t.Logf("%[1]c %[1]d", c)
    }
}

output

=== RUN   TestStringToRune
--- PASS: TestStringToRune (0.00s)
    string_test.go:28: Middle 20013
    string_test.go:28: Hua 21326
    string_test.go:28: Man 20154
    string_test.go:28: Min 27665
    string_test.go:28: A total of 20849
    string_test.go:28: And 21644
    string_test.go:28: 22269 China
PASS

Process finished with exit code 0

Transformation

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

For example code, please visit: https://github.com/wenjianzhang/golearning

Topics: Go github