簡單來說,Go只有兩種字符串表示方式:
使用反引號(`)- Raw string literal:
反斜線(\)不會被轉(zhuǎn)義
可以換行使用雙引號(")- Interpreted sting literal:
反斜線(\)會被轉(zhuǎn)義:轉(zhuǎn)義字符(如,“\n”);或者字符編碼(如,16進(jìn)制編碼:\xNN,unicode編碼:\uNNNN或\Unnnnnnnn,十進(jìn)制編碼(0~255):\nnn)
不可以換行
\' (轉(zhuǎn)義單引號)是非法的
\r 回車符將被忽視
不能使用單引號(')表示字符串,單引號只能用于單個字符(或字符編碼)
示例:
package main
import "fmt"
func main() {
//雙引號
s := "Hello World \n"
fmt.Printf("%s", s)
fmt.Printf("%#x\n", "a") // a 的編碼:\x61
fmt.Println("\x61") // a
fmt.Println("\u0061") // a
fmt.Println("\U00000061") // a
fmt.Printf("%x\n", "中")
fmt.Println("\xe4\xb8\xad文") //中 的編碼
//unicode
for pos, char := range "中\(zhòng)x80文" { // \x80 is an illegal UTF-8 encoding
fmt.Printf("character %#U starts at byte position %d\n", char, pos)
}
fmt.Println("\u4e2d") //中 的編碼
fmt.Println("\U00004e2d") //中 的編碼
//反引號
fmt.Println(`how
are
you \n`) // \n 不轉(zhuǎn)義
//單引號
fmt.Printf("%x\n", 'a') // a的編碼
fmt.Println(string('\x61')) // a
fmt.Println(string('\u0061')) // a
}
輸出:
Hello World
0x61
a
a
a
e4b8ad
中文
character U+4E2D '中' starts at byte position 0
character U+FFFD '?' starts at byte position 3
character U+6587 '文' starts at byte position 4
中
中
how
are
you \n
61
a
a