The Sprint function in the Go programming language is used to generate and return a formatted string. Sprint does not support custom format specifiers, which means only the default formats are used to format the string. It also automatically adds spaces between non-string values passed as arguments but will not do so if either one is a string.
To use the Sprint function, we need to import the fmt Go package that stores the definition of this function. So, we access the function in the package using the . notation: fmt.Sprint.
The definition of the Sprint function inside the fmt package is as follows:
fmt.Sprint takes only a list of a variable number of arguments a ...interface{} which contains a list of all arguments that need to be formatted and returned as a string.
The fmt.Sprint function returns just a single string that it has formatted.
The following example is a simple program where we first generate a new string using the Sprint function and print out to the standard output using the print function.
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to "var year int = 2021// temporary buffervar temp stringtemp = fmt.Sprint(message, year)// printing out the declared variables as a single stringfmt.Print(temp)}
The example above observes how there is no space added between our string variable and our integer variable when it is formatted and stored into temp.
The following example adds another non-string variable to the Sprint arguments:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to july "var day int = 12var year int = 2021// temporary buffervar temp stringtemp = fmt.Sprint(message, day, year)// printing out the declared variables as a single stringfmt.Print(temp)}
Observe how in our second example despite not including a space character the Sprint function automatically adds one between 12 and 2021 but we had to place a space at the end of our variable message.
Free Resources