A multiline string can be useful when you want to show the user of your app in a readable format. This article shows you how you can achieve multiline strings in Go
Strings in Go is a variable-length of characters where each character is represented by one or more bytes of UTF-8 encoded data. It is read-only and immutable which means that you cannot change the value after it is assigned.
awesomeStr:= "My string";
awesomeStr[0] = 'S'; // Throws error from compiler
We can make use of backtick and have it easy to read and write in code. All the indentation is also respected.
package main
import "fmt"
func main() {
str := `Documentation for the usage of the API
*Param 1* - Useful for feature A
*Param 2*- Useful for feature B
`
fmt.Println(str)
}
Output
Documentation for the usage of the API
*Param 1* - Useful for feature A
*Param 2*- Useful for feature B
For more details on Go string literals - https://golang.org/ref/spec#String_literals
You can add \n
character to the string variable to display the items in a new line. This method will work for simple cases but it makes the code messy and hard to read
package main
import "fmt"
func main() {
multiline := "Documentation for the usage of the API\n\n*Param 1* - Useful for feature A\n*Param 2*- Useful for feature B"
fmt.Println(multiline)
}
Output
Documentation for the usage of the API
*Param 1* - Useful for feature A
*Param 2*- Useful for feature B
String interpolation in Go can be achieved using the printf
method from the fmt
package. Here are some examples of String interpolation in Go.
package main
import "fmt"
func main() {
name:= "Student 1"
total:= 426
grade := 'B'
avg := 8.325
fmt.Printf("Name is %s\n", name)
fmt.Printf("Total is %d\n", total)
fmt.Printf("Grade is %c\n", grade)
fmt.Printf("Average is %f\n", avg)
}
Data Type | String interpolation verbs |
---|---|
int | %d |
string | %s |
char | %c |
float | %f |
Try out the string interpolation in Go using the codeshare link
https://www.jdoodle.com/embed/v0/4sKU
Stay tuned by subscribing to our mailing list and joining our Discord community
Sriram is a content creator focused on providing quality content which provides value for the readers. He believe is constant learning and sharing those learning with the group. He is working as a lead developer and bulk of his experience is in working with multiple javascript frameworks such as Angular, React, Svelte. He is passionate about open source technologies and on his free time loves to develop games.
We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.