Skip to content

How to String Formatting in Golang?

Yes, you want to format a string without printing it!

fmt package is your friend when you working with string type, use Sprintf method and it will format your string and return it instead of printing.

func Sprintf(format string, a ...interface{}) string {

This example shows the difference between Sprintf and Printf:

package main

import "fmt"

func main() {

	name := "Morteza"

	// Printf will format and print the result
	fmt.Printf("Hello %s", name)

	// Printf will format and return the result
	greeting := fmt.Sprintf("Hello %s", name)

	fmt.Println(greeting)
}

Leave a Reply

Your email address will not be published. Required fields are marked *