×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang fmt.Sprintf() Function with Examples

Golang | fmt.Sprintf() Function: Here, we are going to learn about the Sprintf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 09, 2021

fmt.Sprintf()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Sprintf() function is an inbuilt function of the fmt package which is used to format according to a format specifier and returns the resulting string.

It accepts two parameters (format string, a ...interface{}) and returns the formatted string.

Syntax:

func Sprintf(format string, a ...interface{}) string

Parameter(s):

  • format : String format with the format verbs.
  • 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.Sprintf() function is a string, it returns the formatted string.

Example 1:

// Golang program to demonstrate the
// example of fmt.Sprintf() function

package main

import (
	"fmt"
)

func main() {
	name := "Alex"
	age := 21

	// Calling fmt.Sprintf() to format the string
	s := fmt.Sprintf("%s is %d years old.", name, age)

	// Prints the formatted string
	fmt.Println("s:", s)

	name = "Alvin Alexander"
	age = 43

	// Calling fmt.Sprintf() to format the string
	s = fmt.Sprintf("%s is %d years old.", name, age)

	// 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.Sprintf() function

package main

import (
	"fmt"
)

func main() {
	x := 10
	y := 20

	// Calling fmt.Sprintf() to format the string
	s1 := fmt.Sprintf("%d + %d = %d", x, y, x+y)
	s2 := fmt.Sprintf("%d - %d = %d", x, y, x-y)
	s3 := fmt.Sprintf("%d * %d = %d", 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 »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.