Golang 单引号、双引号和反引号 - Go语言中文社区

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


前言

我正在学习酷酷的 Golang,可点此查看帖子Golang学习笔记汇总

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


版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/iotisan/article/details/104687737
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢