Whats is the Sprintf function in golang?

The fmt.Sprintf function in the GO programming language is a function used to return a formatted string. fmt.Sprintf supports custom format specifiers and uses a format string to generate the final output string.

sprintf is the actual function, while fmt is the GO package that stores the definition of this function. So to use this function, you must import the fmt package in your file and access the Sprintf function within using the . notation: fmt.Sprintf

Function definition

The definition of the Sprintf function inside the fmt package is as follows:

Parameters

fmt.Sprintf first takes the format string as an argument followed by a variable number of arguments.

  • format: This argument is of type string and represents the string containing custom specifiers that the sprintf uses to format the final output string

  • a ...interface{}: This argument refers to the list of a variable number of arguments that need to be formatted and printed.

Return values

The fmt.Sprintf function returns just a single string that it has formatted.

Common specifiers

Following is a table of the most commonly used format specifiers in GO and their descriptions:

Specifiers Description
%s To print a string
%d To print an integer
%v To print values of all elements in a structure
%+v To print the names and values of all elements in a structure

Example

The following example is a simple program where we first generate a new string using the Sprintf function then print it out using the print function to the console:

package main
import (
"fmt"
)
func main() {
// declaring variables of different datatypes
var message string = "Hello and welcome to"
var year int = 2021
// printing out the declared variables following the format string
var complete_msg = fmt.Sprintf("%s educative in %d", message, year)
fmt.Print(complete_msg)
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved