How to Format a Go String without Printing

To format a string without printing in Go, you can use the fmt.Sprintf() function. The fmt.Sprintf() function takes a format string and any number of arguments and returns a string formatted according to the format string. The syntax is func Sprintf(format string, a …interface{}) string.

Example

package main

import (
  "fmt"
)

func main() {
  name := "Krunal"
  age := 30
  formattedString := fmt.Sprintf("My name is %s and I am %d years old.", name, age)
  fmt.Println("Formatted string:", formattedString)
}

Output

Formatted string: My name is Krunal and I am 30 years old.

In this example, we first define the name and age variables. We then used the fmt.Sprintf() function to format a string using the name and age variables.

Finally, we printed the formatted string to the console using the fmt.Println() function.

Notes

  1. We are using fmt.Println() function to print the formatted string to the console in this example, but you can store it in a variable or use it in any other way you need.
  2. To concatenate values of different types, you may not automatically need to use the Sprintf() function (which requires a format string) as Sprint() function does exactly this.
  3. If you are dealing with complex strings, use the packages text/template and html/template. These packages implement data-driven templates for generating textual output. The html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML. 

That’s it.

Leave a Comment