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 := "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: £

3 反引号的应用场景,为了展示字面量

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)
	};

4 小结

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

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

END


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值