Golang fmt.Sprintf() Function

Golang fmt.Sprintf() function is “used to format according to a format specifier and returns the resulting string.”

Syntax

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

Parameters

  1. format string: This includes some variables along with some strings.
  2. a …interface{}: This is the specified constant variable.

Return Value

The Sprintf() function returns a String and does not print the string. So after storing it in a variable, we can print the string. See the following example.

Example 1: How to Use fmt.Sprintf() function

package main

import (
  "fmt"
)

func main() {
  const name, age = "Krunal", 27
  s := fmt.Sprintf("%s is %d years old.\n", name, age)
  print(s)
}

Output

Krunal is 27 years old.

Example 2

package main

import (
  "fmt"
  "io"
  "os"
)

func main() {
  const num1, num2, num3 = 11, 19, 21

  str := fmt.Sprintf("%d + %d = %d", num1, num2, num3)

  io.WriteString(os.Stdout, str)
}

Output

11 + 19 = 21

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.