Strings
Another important built-in type is string
. Assigning a string is as simple as:
s := "Hello World!"
Strings in Go are a sequence of UTF-8 characters enclosed in double quotes (“).If you use the single quote (‘) you mean one character (encoded in UTF-8) —which is not a string
in Go.
Once assigned to a variable, the string cannot be changed: strings in Go areimmutable. If you are coming from C, note that the following is not legal in Go:
var s string = "hello"
s[0] = 'c'
To do this in Go you will need the following:
s := "hello"
c := []rune(s) 1
c[0] = 'c' 2
s2 := string(c) 3
fmt.Printf("%s\n", s2) 4
Here we convert s
to an array of runes 1. We change the first element ofthis array 2. Then we create a new string s2
with the alteration 3.Finally, we print the string with fmt.Printf
4.
当前内容版权归 Miek Gieben 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Miek Gieben .