aeter
aeter

Reputation: 12720

How do you write multiline strings in Go?

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?

Upvotes: 947

Views: 553850

Answers (13)

Tommaso Resti
Tommaso Resti

Reputation: 5960

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",
)

Upvotes: 6

ceving
ceving

Reputation: 23871

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"

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839214

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`

Upvotes: 1470

Carson
Carson

Reputation: 8138

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.

Upvotes: 3

Bilal Khan
Bilal Khan

Reputation: 129

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)
}

Upvotes: 9

mddkpp at gmail.com
mddkpp at gmail.com

Reputation: 2051

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"

Upvotes: 185

Ofonime Francis
Ofonime Francis

Reputation: 23

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

Upvotes: 2

I159
I159

Reputation: 31199

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
}

Upvotes: 71

ASHWIN RAJEEV
ASHWIN RAJEEV

Reputation: 2891

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.

Upvotes: 17

Prabesh P
Prabesh P

Reputation: 150

you can use raw literals. Example

s:=`stack
overflow`

Upvotes: 3

David
David

Reputation: 947

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)
}

Upvotes: 4

liam
liam

Reputation: 361

You can put content with `` around it, like

var hi = `I am here,
hello,
`

Upvotes: 5

VonC
VonC

Reputation: 1329712

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?"):

 + "`" + ...

Upvotes: 48

Related Questions