Golang的單引號、雙引號與反引號

來源:互聯網
上載者:User

Go語言的字串類型string在本質上就與其他語言的字串類型不同:

  • Java的String、C++的std::string以及Python3的str類型都只是定寬字元序列

  • Go語言的字串是一個用UTF-8編碼的變寬字元序列,它的每一個字元都用一個或多個位元組表示

即:一個Go語言字串是一個任意位元組的常量序列

Golang的雙引號和反引號都可用於表示一個常量字串,不同在於:

  • 雙引號用來建立可解析的字串字面量(支援轉義,但不能用來引用多行)

  • 反引號用來建立原生的字串字面量,這些字串可能由多行組成(不支援任何逸出序列),原生的字串字面量多用於書寫多行訊息、HTML以及Regex

而單引號則用於表示Golang的一個特殊類型:rune,類似其他語言的byte但又不完全一樣,是指:碼點字面量(Unicode code point),不做任何轉義的原始內容。

 

There are two forms: raw string literals and interpreted string literals.

  • Raw string literals are character sequences between back quotes, as in foo .
  • Interpreted string literals are character sequences between double quotes, as in “bar”.

A rune literal represents a rune constant, an integer value identifying a Unicode code point. A rune literal is expressed as one or more characters enclosed in single quotes, as in ‘x’ or ‘\n’. Within the quotes, any character may appear except newline and unescaped single quote. A single quoted character represents the Unicode value of the character itself, while multi-character sequences beginning with a backslash encode values in various formats.

=

根據我找到的資料以及碰到的情況來看, Go語言的單引號一般用來表示「rune literal」 ,即——碼點字面量。

參考連結:
  • https://golang.org/ref/spec#String_literals
  • https://golang.org/ref/spec#Rune_literals
  • http://teapottable.com/blog/starting-out-with-go-lang/
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.