fmt.Sprintf() Function in Golang With Examples

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.