Related Articles

Related Articles

fmt.Sprintf() Function in Golang With Examples
  • Last Updated : 05 May, 2020

In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.

Syntax:

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

Parameters: This function accepts two parameters which are illustrated below:

  • format string: This includes some varbs along with some strings.
  • a …interface{}: This is the specified constant variables.

Returns: It returns the resulting string.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// fmt.Sprintf() function
  
// Including the main package
package main
  
// Importing fmt, io and os
import (
    "fmt"
    "io"
    "os"
)
  
// Calling main
func main() {
  
    // Declaring some const variables
    const name, dept = "GeeksforGeeks", "CS"
  
    // Calling Sprintf() function
    s := fmt.Sprintf("%s is a %s Portal.\n", name, dept)
  
    // Calling WriteString() function to write the
    // contents of the string "s" to "os.Stdout"
    io.WriteString(os.Stdout, s)
  
}

chevron_right


Output:

GeeksforGeeks is a CS Portal.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// fmt.Sprintf() function
  
// Including the main package
package main
  
// Importing fmt, io and os
import (
    "fmt"
    "io"
    "os"
)
  
// Calling main
func main() {
  
    // Declaring some const variables
    const num1, num2, num3 = 5, 10, 15
  
    // Calling Sprintf() function
    s := fmt.Sprintf("%d + %d = %d", num1, num2, num3)
  
    // Calling WriteString() function to write the
    // contents of the string "s" to "os.Stdout"
    io.WriteString(os.Stdout, s)
  
}

chevron_right


Output:

5 + 10 = 15



My Personal Notes arrow_drop_up
Recommended Articles
Page :