您的位置 首页 > 腾讯云社区

Golang 单引号、双引号和反引号---twowinter

文章目录前言1 概述2 示例3 反引号的应用场景,为了展示字面量4 小结END 1 概述

Golang限定字符或者字符串一共三种引号,单引号(’’),双引号("") 以及反引号(``)。反引号就是标准键盘“Esc”按钮下面的那个键。

对应的英文是:Single quote、Double quote、Back quote。

单引号,表示byte类型或rune类型,对应 uint8和int32类型,默认是 rune 类型。byte用来强调数据是raw data,而不是数字;而rune用来表示Unicode的code point。 双引号,才是字符串,实际上是字符数组。可以用索引号访问某字节,也可以用len()函数来获取字符串所占的字节长度。 反引号,表示字符串字面量,但不支持任何转义序列。字面量 raw literal string 的意思是,你定义时写的啥样,它就啥样,你有换行,它就换行。你写转义字符,它也就展示转义字符。 2 示例

参考 https://golangbyexample.com/double-single-back-quotes-go/

package main import ( "fmt" "reflect" "unsafe" ) func main() { //String in double quotes x := "titnforttat" fmt.Println("Priting String in Double Quotes:") fmt.Printf("x is: %sn", x) //String in back quotes y := `titnforttat` fmt.Println("nPriting String in Back Quotes:") fmt.Printf("y is: %sn", y) //Declaring a byte with single quotes var b byte = 'a' fmt.Println("nPriting Byte:") //Print Size, Type and Character fmt.Printf("Size: %dnType: %snCharacter: %cn", unsafe.Sizeof(b), reflect.TypeOf(b), b) //Declaring a rune with single quotes r := '£' fmt.Println("nPriting Rune:") //Print Size, Type, CodePoint and Character fmt.Printf("Size: %dnType: %snUnicode CodePoint: %UnCharacter: %cn", unsafe.Sizeof(r), reflect.TypeOf(r), r, r) //Below will raise a compiler error - invalid character literal (more than one character) //r = 'ab' }

输出:

Priting String in Double Quotes: x is: tit for tat Priting String in Back Quotes: y is: titnforttat Priting Byte: Size: 1 Type: uint8 Character: a Priting Rune: Size: 4 Type: int32 Unicode CodePoint: U+00A3 Character: £3 反引号的应用场景,为了展示字面量package main import ( "log" ) const ( doubleQuote string = "nmain {nconsole.log(event)nreturn retn};n" backQuote string = ` main { console.log(event) }; ` ) func main() { log.Printf("doubleQuote:%vn", doubleQuote[1]) log.Printf("backQuote:%sn", backQuote) }

输出:

doubleQuote:109 backQuote: main { console.log(event) };4 小结

反引号在某些需要展示字符串字面量的场合还是很有用,比如我们要展示一个多行的函数。

单引号则通常用来表示rune类型,展示 unicode。

END ---来自腾讯云社区的---twowinter

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: