1. Double Quota 双引号
常用来定义字符串。
双引号中定义的字符串将支持转义字符。比如\n将输出换行。
2. Back Quota 反引号
常用来定义字符串。
用反引号编码的字符串是原始文本字符串,不接受任何形式的转义。原生的字符串字面量多用于书写多行消息、HTML以及正则表达式。
3. Single quotes 单引号
单引号用来定义一个 byte或者rune。
Go语言中的byte和rune
Go语言中byte和rune实质上就是uint8和int32类型。byte用来强调数据是raw data,而不是数字;而rune用来表示Unicode的code point。golang规范
byte alias for uint8 rune alias for int32
当我们定义 byte时必须要指定类型,如果不指定类型,默认为 rune。一个单引号只允许一个字符。
4. 示例
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
//String in double quotes
x := "tit\nfor\ttat"
fmt.Println("Priting String in Double Quotes:")
fmt.Printf("x is: %s\n", x)
//String in back quotes
y := `tit\nfor\ttat`
fmt.Println("\nPriting String in Back Quotes:")
fmt.Printf("y is: %s\n", y)
//Declaring a byte with single quotes
var b byte = 'a'
fmt.Println("\nPriting Byte:")
//Print Size, Type and Character
fmt.Printf("Size: %d\nType: %s\nCharacter: %c\n", 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: %d\nType: %s\nUnicode CodePoint: %U\nCharacter: %c\n", unsafe.Sizeof(r), reflect.TypeOf(r), r, r)
//Below will raise a compiler error - invalid character literal (more than one character)
//r = 'ab'
}
参考资料
https://nanxiao.me/golang-byte-rune/
https://golangbyexample.com/double-single-back-quotes-go/
网友评论