Golang限定字符或者字符串一共三种引号,单引号(’’),双引号("") 以及反引号(``)。反引号就是标准键盘“Esc”按钮下面的那个键。
对应的英文是:Single quote、Double quote、Back quote。
参考 https://golangbyexample.com/double-single-back-quotes-go/
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'
}
输出:
Priting String in Double Quotes:
x is: tit
for tat
Priting String in Back Quotes:
y is: tit\nfor\ttat
Priting Byte:
Size: 1
Type: uint8
Character: a
Priting Rune:
Size: 4
Type: int32
Unicode CodePoint: U+00A3
Character: £
package main
import (
"log"
)
const (
doubleQuote string = "\nmain {\nconsole.log(event)\nreturn ret\n};\n"
backQuote string = `
main {
console.log(event)
};
`
)
func main() {
log.Printf("doubleQuote:%v\n", doubleQuote[1])
log.Printf("backQuote:%s\n", backQuote)
}
输出:
doubleQuote:109
backQuote:
main {
console.log(event)
};
反引号在某些需要展示字符串字面量的场合还是很有用,比如我们要展示一个多行的函数。
单引号则通常用来表示rune类型,展示 unicode。