【Goloang】字符串/Rune - 單引號(') 雙引號(") 反引號(`) 的區(qū)別

簡單來說,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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容