Home »
Golang »
Golang Reference
Golang fmt.Sprintln() Function with Examples
Golang | fmt.Sprintln() Function: Here, we are going to learn about the Sprintln() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 10, 2021
fmt.Sprintln()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Sprintln() function is an inbuilt function of the fmt package which is used to format using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.
It accepts one parameter (a ...interface{}) and returns the formatted string.
Syntax:
func Sprintln(a ...interface{}) string
Parameter(s):
- a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.
Return Value:
The return type of the fmt.Sprintln() function is a string, it returns the formatted string.
Example 1:
// Golang program to demonstrate the
// example of fmt.Sprintln() function
package main
import (
"fmt"
)
func main() {
name := "Alex"
age := 21
// Calling fmt.Sprintln() to format the string
s := fmt.Sprintln(name, " is ", age, " years old.")
// Prints the formatted string
fmt.Println("s:", s)
name = "Alvin Alexander"
age = 43
// Calling fmt.Sprintln() to format the string
s = fmt.Sprintln(name, " is ", age, " years old.")
// Prints the formatted string
fmt.Println("s:", s)
}
Output:
s: Alex is 21 years old.
s: Alvin Alexander is 43 years old.
Example 2:
// Golang program to demonstrate the
// example of fmt.Sprintln() function
package main
import (
"fmt"
)
func main() {
x := 10
y := 20
// Calling fmt.Sprintln() to format the string
s1 := fmt.Sprintln(x, " + ", y, " = ", x+y)
s2 := fmt.Sprintln(x, " - ", y, " = ", x-y)
s3 := fmt.Sprintln(x, " * ", y, " = ", x*y)
// Prints the formatted string
fmt.Println("Addition:", s1)
fmt.Println("Subtraction:", s2)
fmt.Println("Multiplication:", s3)
}
Output:
Addition: 10 + 20 = 30
Subtraction: 10 - 20 = -10
Multiplication: 10 * 20 = 200
Golang fmt Package »