Go语言程序演示转义字符


在 Go 编程语言中,有几种特殊类型的转义字符。每种转义字符的使用都实现了不同的功能。我们将在接下来的示例中逐一讨论它们。

示例 1

在本例中,我们将编写一个 Go 语言程序来演示反斜杠 (//) 字符。它用于在程序输出中显示斜杠。

package main
import "fmt"

func main() {
	fmt.Println("Program to display a backslash using in the program")
}

输出

Program to display a backslash using in the program\

示例 2

在本例中,我们将编写一个 Go 语言程序来演示 ASCII 响铃字符。它由 \a 转义字符字面量显示。

package main
import "fmt"

func main() {
    fmt.Println("Go landuage program to display an ASCII bell (BEL): \a")
}

输出

Go landuage program to display an ASCII bell (BEL): 

示例 3

在本例中,我们将编写一个 Go 语言程序来演示换行符。它由 \n 转义字符字面量显示,用于开始新的一行。在此字符之后写入的字符串/数字将出现在新的一行。

package main
import "fmt"

func main() {
	fmt.Println("Go landuage program to show a line feed. \nThis string will be displayed in a new line.")
}

输出

Go landuage program to show a line feed. 
This string will be displayed in a new line.

示例 4

在本例中,我们将编写一个 Go 语言程序来演示回车符。它由 \r 转义字符字面量显示,用于开始新的一行。换行符和回车符的区别在于,回车符在新行的开头留出一个小的空格。

package main
import "fmt"

func main() {
	fmt.Println("Go languaage program to display carriage return (CR): \r This is second statement and appears in the new line.")
}

输出

Go languaage program to display carriage return (CR): 
 This is second statement and appears in the new line.

示例 5

在本例中,我们将编写一个 Go 语言程序来演示水平制表符。它由 \t 转义字符字面量显示,用于在显示数据的后面留出一个空格。

package main
import "fmt"

func main() {
	fmt.Println("Go language program to display ASCII horizontal tab (TAB): \n This is second statement and appears after a space")
}

输出

Go language program to display ASCII horizontal tab (TAB): 
 This is second statement and appears after a space

示例 6

在本例中,我们将编写一个 Go 语言程序来演示双引号。它由 \” 转义字符字面量显示,用于将输入在其内部的数据封装在双引号中。

package main
import "fmt"

func main() {
   fmt.Println("Golang program to display Double quote string literal (∖"this will come in quotations ∖"): ")
}

输出

Golang program to display Double quote string literal ("this will come in quotations"):

示例 7

在本例中,我们将编写一个 Go 语言程序来演示 Unicode 转义字符。它由 \u 显示,用于在程序中包含十六进制数字。

package main

import "fmt"

func main() {
	fmt.Printf("Go language program to display a Unicode code point (Heart): %c", '\u2665')
}

输出

Go language program to display a Unicode code point (Heart): ♥

示例 8

在本例中,我们将编写一个 Go 语言程序来演示十六进制转义字符。它由 \x 显示,用于通过其十六进制代码表示字符。

package main
import "fmt"

func main() {
	fmt.Printf("Go language program to show Hexadecimal escape sequence character (Star): %c", '\x2a')
}

输出

Go language program to show Hexadecimal escape sequence character (Star): *

结论

我们已经成功地编译并执行了一个 Go 语言程序来演示转义字符以及示例。在本文中,我们展示了不同的转义字符字面量及其用法。

更新于: 2023年2月13日

1K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.