前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang 单引号、双引号和反引号

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

作者头像
twowinter
发布2020-04-16 23:54:13
13.6K0
发布2020-04-16 23:54:13
举报
文章被收录于专栏:twowintertwowinter

文章目录
  • 前言
  • 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/

代码语言:javascript
复制
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'
}

输出:

代码语言:javascript
复制
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 反引号的应用场景,为了展示字面量

代码语言:javascript
复制
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)
}

输出:

代码语言:javascript
复制
doubleQuote:109
backQuote:
	main {
		console.log(event)
	};

4 小结

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

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

END


本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1 概述
  • 2 示例
  • 3 反引号的应用场景,为了展示字面量
  • 4 小结
  • END
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com