创建字符串
创建字符串的最直接方法是编写-
var greeting = "Hello world!"
每当在代码中遇到字符串字面量时,编译器都会创建一个字符串对象,其值在这种情况下为“Hello world!”。字符串字面量包含有效的UTF-8序列,称为符文。字符串包含任意字节。
package main
import "fmt"
func main() {
var greeting = "Hello world!"
fmt.Printf("normal string: ")
fmt.Printf("%s", greeting)
fmt.Printf("\n")
fmt.Printf("hex bytes: ")
for i := 0; i < len(greeting); i++ {
fmt.Printf("%x ", greeting[i])
}
fmt.Printf("\n")
const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"
/*q flag escapes unprintable characters, with + flag it escapses non-ascii
characters as well to make output unambigous */
fmt.Printf("quoted string: ")
fmt.Printf("%+q", sampleText)
fmt.Printf("\n")
}
尝试一下
这将产生以下结果-
normal string: Hello world!
hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21
quoted string: "\xbd\xb2=\xbc \u2318"
注 – 字符串字面量是不可变的,因此一旦创建字符串文字就无法更改。