Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

fmt.Sprintf() Function in Golang With Examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:




// 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)
  
}

Output:

GeeksforGeeks is a CS Portal.

Example 2:




// 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)
  
}

Output:

5 + 10 = 15

My Personal Notes arrow_drop_up
Last Updated : 05 May, 2020
Like Article
Save Article
Similar Reads