Home »
Golang »
Golang Reference
Golang fmt.Sprint() Function with Examples
Golang | fmt.Sprint() Function: Here, we are going to learn about the Sprint() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 09, 2021
fmt.Sprint()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Sprint() 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 added between operands when neither is a string.
It accepts one parameter (a ...interface{}) and returns the formatted string.
Syntax:
func Sprint(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.Sprint() function is a string, it returns the formatted string.
Example 1:
// Golang program to demonstrate the
// example of fmt.Sprint() function
package main
import (
"fmt"
)
func main() {
name := "Alex"
age := 21
// Calling fmt.Sprint() to format the string
s := fmt.Sprint(name, " is ", age, " years old.")
// Prints the formatted string
fmt.Println("s:", s)
name = "Alvin Alexander"
age = 43
// Calling fmt.Sprint() to format the string
s = fmt.Sprint(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.Sprint() function
package main
import (
"fmt"
)
func main() {
x := 10
y := 20
// Calling fmt.Sprint() to format the string
s1 := fmt.Sprint(x, " + ", y, " = ", x+y)
s2 := fmt.Sprint(x, " - ", y, " = ", x-y)
s3 := fmt.Sprint(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 »