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

huangapple go评论126阅读模式
英文:

How do you write multiline strings in Go?

问题

Go语言有类似于Python的多行字符串吗?

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

英文:

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

<!-- language: lang-python -->

&quot;&quot;&quot;line 1
line 2
line 3&quot;&quot;&quot;

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

答案1

得分: 1346

根据语言规范,您可以使用原始字符串字面量,其中字符串由反引号而不是双引号界定。

`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`

答案2

得分: 173

你可以这样写:

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

这与以下写法相同:

"line 1line 2line 3"

与使用反引号不同,它会保留转义字符。请注意,"+" 必须在 'leading' 行上 - 例如,以下写法会生成错误:

"line 1"
+"line 2"
英文:

You can write:

&quot;line 1&quot; +
&quot;line 2&quot; +
&quot;line 3&quot;

which is the same as:

&quot;line 1line 2line 3&quot;

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:

&quot;line 1&quot;
+&quot;line 2&quot;

答案3

得分: 63

使用原始字符串字面量来表示多行字符串:

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将只是被打印出来。
    // 但是换行符也在其中。
    fmt.Print(multiline)
}

字符串连接

可能你有一行很长的字符串,你想要换行,但是你不需要在其中插入换行符。在这种情况下,你可以使用字符串连接。

func main(){
    multiline := &quot;line &quot; +
            &quot;by line &quot; +
            &quot;and line &quot; +
            &quot;after line&quot;

    fmt.Print(multiline) // 这里没有换行符
}

由于" "是解释的字符串字面量,转义字符将被解释。

func main(){
    multiline := &quot;line &quot; +
            &quot;by line \n&quot; +
            &quot;and line \n&quot; +
            &quot;after line&quot;

    fmt.Print(multiline) // 换行符被解释为 \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 := &quot;line &quot; +
            &quot;by line &quot; +
            &quot;and line &quot; +
            &quot;after line&quot;

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

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

func main(){
    multiline := &quot;line &quot; +
            &quot;by line \n&quot; +
            &quot;and line \n&quot; +
            &quot;after line&quot;

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

答案4

得分: 47

String literals

  • 原始字符串字面量支持多行(但转义字符不会被解释)
  • 解释字符串字面量会解释转义字符,比如\n

但是,如果你的多行字符串中需要包含一个反引号(`),那么你必须使用一个解释字符串字面量:

`第一行
  第二行 ` +
&quot;`&quot; + `第三行
第四行`

你不能直接在原始字符串字面量中放置一个反引号(`xx`)。
你必须使用(如“如何在反引号字符串中放置一个反引号?”中所解释的):

 + &quot;`&quot; + ...
英文:

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 ` +
&quot;`&quot; + `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?"):

 + &quot;`&quot; + ...

答案5

得分: 16

使用反引号可以创建多行字符串:

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 &quot;fmt&quot;

func main() {

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

	fmt.Printf(&quot;%s&quot;, 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.

答案6

得分: 8

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

package main

import (
	"fmt"
)

func main() {
    // 多行字符串
	str := `This is a
multiline
string.`
	fmt.Println(str + "\n")
	
    // 带有制表符的多行字符串
	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 (
	&quot;fmt&quot;
)

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

答案7

得分: 5

你可以用``将内容包起来,就像

var hi = `我在这里,
你好,
`
英文:

You can put content with `` around it, like

var hi = `I am here,
hello,
`

答案8

得分: 4

你在go语言中必须非常小心格式和行间距,每一点都很重要,这里有一个可运行的示例,你可以尝试一下 https://play.golang.org/p/c0zeXKYlmF

package main

import "fmt"

func main() {
    testLine := `这是测试行1
这是测试行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 &quot;fmt&quot;

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

答案9

得分: 3

你可以使用原始字符串字面量。
示例

s := `stack
overflow`
英文:

you can use raw literals.
Example

s:=`stack
overflow`

答案10

得分: 3

对于我来说,我需要使用`<sup>重音符号/反引号</sup>并且只是写一个简单的测试

+ "&quot;`&quot; + ..."

很丑陋和不方便

所以我拿一个字符<sup>例如:🐬 U+1F42C</sup>来替换它


一个演示

myLongData := `line1
line2 &#128044;aaa&#128044;
line3
` // 可能你可以使用IDE来帮助你将所有的`替换为&#128044;
myLongData = strings.ReplaceAll(myLongData, "&quot;&#128044;&quot;", "&quot;`&quot;")

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

性能和内存评估

<code>+ ""&quot;"&lt;/code&gt; v.s. &lt;code&gt;replaceAll(, "&quot;&#128044;&quot;", "&quot;")</code>

package main

import (
	"strings"
	"testing"
)

func multilineNeedGraveWithReplaceAll() string {
	return strings.ReplaceAll(`line1
line2
line3 &#128044;aaa&#128044;`, "&quot;&#128044;&quot;", "&quot;`&quot;")
}

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

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    查看更多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

是的,<code>+ ""`""</code>比其他的性能更好。

英文:

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

+ &quot;`&quot; + ...

is ugly and inconvenient

so I take a character<sup>for example: 🐬 U+1F42C</sup> to replace it


a demo

myLongData := `line1
line2 &#128044;aaa&#128044;
line3
` // maybe you can use IDE to help you replace all ` to &#128044;
myLongData = strings.ReplaceAll(myLongData, &quot;&#128044;&quot;, &quot;`&quot;)

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

Performance and Memory Evaluation

<code>+ "`"</code> v.s. <code>replaceAll(, "🐬", "`")</code>

package main

import (
	&quot;strings&quot;
	&quot;testing&quot;
)

func multilineNeedGraveWithReplaceAll() string {
	return strings.ReplaceAll(`line1
line2
line3 &#128044;aaa&#128044;`, &quot;&#128044;&quot;, &quot;`&quot;)
}

func multilineNeedGraveWithPlus() string {
	return `line1
line2
line3` + &quot;`&quot; + &quot;aaa&quot; + &quot;`&quot;
}

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

func BenchmarkMultilineWithPlus(b *testing.B) {
	for i := 0; i &lt; 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 <code>+ "`"</code> has a better performance than the other.

答案11

得分: 1

对于我来说,如果添加\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(&quot;Hello World\nHow are you doing today\nHope all is well with your go\nAnd code&quot;)

Else you can use the raw string

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

答案12

得分: 0

我使用+与一个空的第一个字符串。这样可以得到一个相对可读的格式,并且对于const也有效。

英文:

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

const jql = &quot;&quot; +
	&quot;cf[10705] = &#39;%s&#39; and &quot; +
	&quot;status = 10302 and &quot; +
	&quot;issuetype in (10002, 10400, 10500, 10501) and &quot; +
	&quot;project = 10000&quot;

huangapple
  • 本文由 发表于 2011年10月29日 02:44:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/7933460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定