Write Multiline Strings in Go
A multiline string is very long that are split into multiple lines. Generally, multiline strings provide better readability. Many programming languages, such as Python, Java, C# etc support multiline strings.
Create Multiline strings in Go
Let us look at different ways to write multiline strings in Golang while declaring and assigning string values to variables.
Raw String Literals
Raw string literals are the character sequences that are enclosed within backticks. The raw string literal supports multiline string, but escaped characters are not interpreted.
Let us take a simple example to demonstrate.
package main
import "fmt"
func main() {
var text string = `This is an
example of
multiline string
in Go programming`
// Prints the multiline string
fmt.Println(text)
var description string = `Welcome to \n
Golang Tutorial`
// Note the escape character \n in the multiline string is printed as-is
fmt.Println(description)
}
Output
This is an
example of
multiline string
in Go programming
Welcome to \n
Golang Tutorial
Notice that the \n is not interpreted and it will be printed as-is.
Concatenation of Strings
The other alternative way is to concatenate multiple strings using a +
operator to achieve multiline string.
Here the multiple strings are enclosed within the normal quotes ""
and concatenated using a +
operator. Unlike the backticks, this will preserve all the escape characters in the string.
Let us take an example to demonstrate the same.
package main
import "fmt"
func main() {
var text string = "This is an \n" +
"example of \t" +
"multiline string " +
"in Go programming"
// Prints the multiline string
fmt.Println(text)
}
Output
This is an
example of multiline string in Go programming
Note: The +
operator should be at the leading side of the string; else it will throw an error.
Wrong Usage
var text = "line 1"
+"line 2"
Correct Usage
var text = "line 1"+
"line 2"
Conclusion
Multiline string is a long string that are split into multiple lines. In Golang, there are two ways to create multiline strings.
- Using Raw string literals (string enclosed in backticks)
- String Concatenation