How to Use Heard Documents in Golang

Golang

In Go, you can use a multi-line string literals, often called “heredoc” or “here document”, by using the backtick (`) character.

Here is an example:

package main

import "fmt"

func main() {
    multiLineStr := `Hello
    world`
    fmt.Println(multiLineStr)
}

This code will print “Hello world”.

You can also use this feature to store JSON or XML data as a string.

package main

import "fmt"

func main() {
    jsonStr := `{
    "name": "John",
    "age": 30,
    "city": "New York"
    }`
    fmt.Println(jsonStr)
}

This can be useful when dealing with multi-line JSON data, for example.

Also, Keep in mind that indentation or white spaces in here documents will be treated as part of the string, which might be useful in some case and also could be problematic in other.

タイトルとURLをコピーしました