What is the Sprintln function in golang?
The Sprintln function in the Go programming language generates and returns a formatted string. Sprintln does not support custom format specifiers, which means only that the default formats are used to format the string. It also automatically adds spaces between all values passed as arguments regardless of data type, and a newline is added at the end of the formatted string.
To use the Sprintln function, we need to import the fmt Go package that stores the definition of this function. We access the function in the package using the . notation: fmt.Sprintln.
Function definition
The definition of the Sprintln function inside the fmt package is as follows:
Parameters
fmt.Sprintln 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.
Return values
The fmt.Sprintln function returns just a single string that it has formatted.
Example
The following example is a simple program where we first generate a new string using the Sprintln 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.Sprintln(message, year)// printing out the declared variables as a single stringfmt.Print(temp)}
The example above observes how space is added between our string variable and our integer variable when it is formatted and stored into temp. This is what makes it different from the Sprint function.
The following example adds another non-string variable to the Sprintln 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.Sprintln(message, day, year)// printing out the declared variables as a single stringfmt.Print(temp)}
We do not need to place and space characters ourselves, as the Sprintln function adds these spaces automatically, regardless of the data type of its arguments.
Free Resources