How to Write Multiline Strings in Go
String
in Go
String in Go is slightly different from other languages. In Go, String
is a sequence of one or more characters where each character is denoted by one or more character sets in UTF-8
encoding. Due to this feature, Go string
can even have text formed from a mixture of many languages in the world. We can represent string by enclosing a piece of text in double-quotes ""
.
package main
import "fmt"
func main() {
wish := "We will get victory soon!!"
fmt.Println(wish)
}
Output:
We will get victory soon!!
Multiline Strings in Go
Writing multi-line strings is required while working with large strings such as SQL, HTML or XML in Go. If anyone is from Python background, he/she might know triple double quotes are used for multi-line strings. In this post, we will discuss various techniques to write multi-line strings in Go.
Hard-Coded Method
This is the simplest and naive approach to solve the problem but it is tedious as we need to line separate Println()
statements for every newline.
package main
import "fmt"
func main() {
fmt.Println("Printing ")
fmt.Println("multiline Strings ")
fmt.Println("in Go!!")
}
Output:
Printing
multiline Strings
in Go!!
Raw String Literals
Using backquote (`) character treats escape sequences such as \n, \t
as a string literal and this allows us to write multi-line strings.
package main
import "fmt"
func main() {
multi_line := `Hey!! we
are going to
write multiline strings
in Go.
`
fmt.Printf("%s", multi_line)
}
Output:
Hey!! we
are going to
write multiline strings
in Go.
Interpreted String Literals
If we wish to use escape characters like \n, \t
, we should use double quotes to write multiline strings in Go.
package main
import "fmt"
func main() {
multi_line := "Hey!! we \n" +
"are going to \n" +
"write multiline strings\n" +
"in Go.\n"
fmt.Printf("%s", multi_line)
}
Output:
Hey!! we
are going to
write multiline strings
in Go.
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn