20

Go 语言中的字符串

 4 years ago
source link: http://blog.huangz.me/2020/string-in-go.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

字符串字面量可以包含转义字符, 如第 2 章提到的 \n 。 如果你想要的是字符 \n 本身而不是一个新的文本行, 那么你可以像代码清单 9-1 所示的那样, 使用反引号( ` )而不是双引号( " )来包围文本。 使用反引号包围的字符串被称为原始字符串字面量。

代码清单 9-1 原始字符串字面量: raw.go

fmt.Println("peace be upon you\nupon you be peace")
fmt.Println(`strings can span multiple lines with the \n escape sequence`)

执行这段代码将产生以下输出:

peace be upon you
upon you be peace
strings can span multiple lines with the \n escape sequence

跟普通字符串字面量不同的是, 原始字符串字面量可以在代码里面跨越多个文本行, 就像代码清单 9-2 所示的那样。

代码清单 9-2 跨越多行的原始字符串字面量: raw-lines.go

fmt.Println(`
    peace be upon you
    upon you be peace`)

执行这段代码将产生以下输出,并且字符串中用于缩进的制表符也被正确地打印了出来:

     peace be upon you
     upon you be peace

正如代码清单 9-3 所示, 无论是字符串字面量还是原始字符串字面量, 最终都将变成字符串。

代码清单 9-3 字符串类型: raw-type.go

fmt.Printf("%v is a %[1]T\n", "literal string")    // 打印出 “literal string is a string”
fmt.Printf("%v is a %[1]T\n", `raw string literal`)    //  打印出 “raw string literal is a string”

Note

本文摘录自《Go语言趣学指南》第 9 章, 请访问 gpwgcn.com 以获取更多相关信息。

bmy2Qj3.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK