如何在 Go 中编写多行字符串?

发布于 2024-12-12 08:17:50 字数 161 浏览 0 评论 0原文

Go 是否有类似于 Python 的多行字符串的功能:

"""line 1
line 2
line 3"""

如果没有,那么编写跨多行字符串的首选方式是什么?

Does Go have anything similar to Python's multiline strings:

"""line 1
line 2
line 3"""

If not, what is the preferred way of writing strings spanning multiple lines?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

电影里的梦 2024-12-19 08:17:50

根据语言规范,您可以使用原始字符串文字,其中字符串被分隔用反引号代替双引号。

`line 1
line 2
line 3`

According to the language specification, you can use a raw string literal, where the string is delimited by backticks instead of double quotes.

`line 1
line 2
line 3`
2024-12-19 08:17:50

您可以编写:

"line 1" +
"line 2" +
"line 3"

与:

"line 1line 2line 3"

与使用反引号不同,它将保留转义字符。请注意,“+”必须位于“前导”行 - 例如,以下内容将生成错误:

"line 1"
+"line 2"

You can write:

"line 1" +
"line 2" +
"line 3"

which is the same as:

"line 1line 2line 3"

Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line - for instance, the following will generate an error:

"line 1"
+"line 2"
心碎的声音 2024-12-19 08:17:50

对多行字符串使用原始字符串文字:

func main(){
    multiline := `line 
by line
and line
after line`
}

原始字符串文字

原始字符串文字是反引号之间的字符序列,如 `foo` 中。引号内可以出现除反引号之外的任何字符。

一个重要的部分是,原始文字不仅仅是多行,而且多行并不是它的唯一目的。

原始字符串文字的值是由引号之间的未解释(隐式 UTF-8 编码)字符组成的字符串;特别是,反斜杠没有特殊含义......

因此转义符不会被解释,并且刻度之间的新行将是真正的新行

func main(){
    multiline := `line 
by line \n
and line \n
after line`

    // \n will be just printed. 
    // But new lines are there too.
    fmt.Print(multiline)
}

连接

可能你有很长的一行,你想打破它,并且你不需要在其中添加新行。在这种情况下,您可以使用字符串连接。

func main(){
    multiline := "line " +
            "by line " +
            "and line " +
            "after line"

    fmt.Print(multiline) // No new lines here
}

由于“”被解释为字符串文字转义将被解释。

func main(){
    multiline := "line " +
            "by line \n" +
            "and line \n" +
            "after line"

    fmt.Print(multiline) // New lines as interpreted \n
}

Use raw string literals for multi-line strings:

func main(){
    multiline := `line 
by line
and line
after line`
}

Raw string literals

Raw string literals are character sequences between back quotes, as in `foo`. Within the quotes, any character may appear except back quote.

A significant part is that is raw literal not just multi-line and to be multi-line is not the only purpose of it.

The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning...

So escapes will not be interpreted and new lines between ticks will be real new lines.

func main(){
    multiline := `line 
by line \n
and line \n
after line`

    // \n will be just printed. 
    // But new lines are there too.
    fmt.Print(multiline)
}

Concatenation

Possibly you have long line which you want to break and you don't need new lines in it. In this case you could use string concatenation.

func main(){
    multiline := "line " +
            "by line " +
            "and line " +
            "after line"

    fmt.Print(multiline) // No new lines here
}

Since " " is interpreted string literal escapes will be interpreted.

func main(){
    multiline := "line " +
            "by line \n" +
            "and line \n" +
            "after line"

    fmt.Print(multiline) // New lines as interpreted \n
}
ゃ懵逼小萝莉 2024-12-19 08:17:50

来自 字符串文字

  • 原始字符串文字支持多行(但不解释转义字符)
  • 解释字符串文字解释转义字符,例如“\n”。

但是,如果您的多行字符串必须包含反引号 (`),那么您将必须使用解释的字符串文字:

`line one
  line two ` +
"`" + `line three
line four`

您不能直接将反引号 (`) 放入原始字符串文字 (``xx\)。
您必须使用(如“如何在反引号字符串中放置反引号?”中所述):

 + "`" + ...

From String literals:

  • raw string literal supports multiline (but escaped characters aren't interpreted)
  • interpreted string literal interpret escaped characters, like '\n'.

But, if your multi-line string has to include a backquote (`), then you will have to use an interpreted string literal:

`line one
  line two ` +
"`" + `line three
line four`

You cannot directly put a backquote (`) in a raw string literal (``xx\).
You have to use (as explained in "how to put a backquote in a backquoted string?"):

 + "`" + ...
淡紫姑娘! 2024-12-19 08:17:50

Go 和多行字符串

使用反引号,您可以拥有多行字符串:

package main

import "fmt"

func main() {

    message := `This is a 
Multi-line Text String
Because it uses the raw-string back ticks 
instead of quotes.
`

    fmt.Printf("%s", message)
}

不要使用双引号 (“) 或单引号符号 ('),而是使用反引号来定义字符串的开头和结尾。然后你可以将它绕行。

如果您缩进字符串,请记住空格将
计数。

请检查 playground 并用它做实验。

Go and multiline strings

Using back ticks you can have multiline strings:

package main

import "fmt"

func main() {

    message := `This is a 
Multi-line Text String
Because it uses the raw-string back ticks 
instead of quotes.
`

    fmt.Printf("%s", message)
}

Instead of using either the double quote (“) or single quote symbols (‘), instead use back-ticks to define the start and end of the string. You can then wrap it across lines.

If you indent the string though, remember that the white space will
count.

Please check the playground and do experiments with it.

日裸衫吸 2024-12-19 08:17:50

在 Go 中创建多行字符串实际上非常简单。声明或分配字符串值时只需使用反引号 (`) 字符即可。

package main

import (
    "fmt"
)

func main() {
    // String in multiple lines
    str := `This is a
multiline
string.`
    fmt.Println(str + "\n")
    
    // String in multiple lines with tab
    tabs := `This string
        will have
        tabs in it`
    fmt.Println(tabs)
}

Creating a multiline string in Go is actually incredibly easy. Simply use the backtick (`) character when declaring or assigning your string value.

package main

import (
    "fmt"
)

func main() {
    // String in multiple lines
    str := `This is a
multiline
string.`
    fmt.Println(str + "\n")
    
    // String in multiple lines with tab
    tabs := `This string
        will have
        tabs in it`
    fmt.Println(tabs)
}
夜巴黎 2024-12-19 08:17:50

对于那些可读性比性能更重要的用例,我建议使用这种简单的方法:

func multiline(parts ...string) string {
    return strings.Join(parts, "\n")
}

这就是你使用它的方式:

multiline(
  "this",
  "is a",
  "multiline",
  "text",
),

它生成:

"this\nis a\nmultiline\ntext"

基本上

This
is a
multiline
text

为什么我更喜欢它而不是反引号?

因为您可以使内容保持一致且易于阅读:

// With backticks
aYmlList := `- first_name: John
  last_name: Doe
- first_name: John
  last_name: McClane`

// With multiline method
aYmlList := multiline(
  "- first_name: John",
  "  last_name: Doe",
  "- first_name: John",
  "  last_name: McClane",
)

For those use cases where readability is more important than performance then i'd suggest this simple method:

func multiline(parts ...string) string {
    return strings.Join(parts, "\n")
}

This is how you use it:

multiline(
  "this",
  "is a",
  "multiline",
  "text",
),

It generates:

"this\nis a\nmultiline\ntext"

basically

This
is a
multiline
text

Why i like it more than the backticks?

Because you can keep things aligned and easy to read:

// With backticks
aYmlList := `- first_name: John
  last_name: Doe
- first_name: John
  last_name: McClane`

// With multiline method
aYmlList := multiline(
  "- first_name: John",
  "  last_name: Doe",
  "- first_name: John",
  "  last_name: McClane",
)
魄砕の薆 2024-12-19 08:17:50

您可以在内容周围加上``,例如

var hi = `I am here,
hello,
`

You can put content with `` around it, like

var hi = `I am here,
hello,
`
滥情稳全场 2024-12-19 08:17:50

你必须非常小心 go 中的格式和行距,一切都很重要,这里是一个工作示例,尝试一下 https://play.golang.org/p/c0zeXKYlmF

package main

import "fmt"

func main() {
    testLine := `This is a test line 1
This is a test line 2`
    fmt.Println(testLine)
}

You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF

package main

import "fmt"

func main() {
    testLine := `This is a test line 1
This is a test line 2`
    fmt.Println(testLine)
}
燕归巢 2024-12-19 08:17:50

您可以使用原始文字。
例子

s:=`stack
overflow`

you can use raw literals.
Example

s:=`stack
overflow`
雾里花 2024-12-19 08:17:50

对我来说,我需要使用 ` 重音/反引号 和只写一个简单的测试

+ "`" + ...

是丑陋且不方便的

,所以我以一个字符为例:

For me, I need to use ` grave accent/backquote and just write a simple test

+ "`" + ...

is ugly and inconvenient

so I take a characterfor example: ???? U+1F42C to replace it


a demo

myLongData := `line1
line2 ????aaa????
line3
` // maybe you can use IDE to help you replace all ` to ????
myLongData = strings.ReplaceAll(myLongData, "????", "`")

Go Playground

Performance and Memory Evaluation

+ "`" v.s. replaceAll(, "????", "`")

package main

import (
    "strings"
    "testing"
)

func multilineNeedGraveWithReplaceAll() string {
    return strings.ReplaceAll(`line1
line2
line3 ????aaa????`, "????", "`")
}

func multilineNeedGraveWithPlus() string {
    return `line1
line2
line3` + "`" + "aaa" + "`"
}

func BenchmarkMultilineWithReplaceAll(b *testing.B) {
    for i := 0; i < b.N; i++ {
        multilineNeedGraveWithReplaceAll()
    }
}

func BenchmarkMultilineWithPlus(b *testing.B) {
    for i := 0; i < b.N; i++ {
        multilineNeedGraveWithPlus()
    }
}

cmd

go test -v -bench=. -run=none -benchmem    see more testing.B

output

goos: windows
goarch: amd64
pkg: tutorial/test
cpu: Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
BenchmarkMultilineWithReplaceAll
BenchmarkMultilineWithReplaceAll-8    12572316      89.95 ns/op   24 B/op  1 allocs/op
BenchmarkMultilineWithPlus
BenchmarkMultilineWithPlus-8          1000000000   0.2771 ns/op    0 B/op  0 allocs/op
PASS
ok      tutorial/test   7.566s

Yes, The + "`" has a better performance than the other.

只等公子 2024-12-19 08:17:50

对我来说,如果添加 \n 不是问题,我就使用这个。

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

否则您可以使用原始字符串

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `

For me this is what I use if adding \n is not a problem.

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

Else you can use the raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `
最冷一天 2024-12-19 08:17:50

我将 + 与第一个空字符串一起使用。这允许某种可读的格式,并且适用于 const。

const jql = "" +
    "cf[10705] = '%s' and " +
    "status = 10302 and " +
    "issuetype in (10002, 10400, 10500, 10501) and " +
    "project = 10000"

I use the + with an empty first string. This allows a somehow readable format and it works for const.

const jql = "" +
    "cf[10705] = '%s' and " +
    "status = 10302 and " +
    "issuetype in (10002, 10400, 10500, 10501) and " +
    "project = 10000"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文