golang

Golang Sprintf

The sprinft function in Go is used to perform string formatting and return the resulting string. The sprintf function supports various formatting options.

In this brief article, we will discuss how to use the sprinf function in the Go programming language.

Golang Sprintf Function

The sprinf function is defined in the fmt package. Hence, we need to import it before use. We can do this with a simple import line as:

import "fmt"

Once imported, we can use the function. The function syntax is as defined below:

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

The function takes a formatted string and an interface as the parameter. The function then returns the string without printing it. This means we can save the returned value as a variable.

Sprintf Formatting Specifiers

The sprintf function supports a number of formatting specifiers. The following are some of the common specifiers.

  1. %d – Print an integer
  2. %f – Print a float, lowercase.
  3. %F – Float Uppercase.
  4. %s – Print a string.
  5. %o – octal integer.
  6. %b – binary.
  7. %X – Hexadecimal, uppercase.
  8. %x – hexadecimal, lowercase.
  9. %e – scientific notation, lowercase.
  10. %E – scientific notation, uppercase.
  11. %q – quoted character.
  12. %U – Unicode
  13. %t = Boolean.
  14. %p – Pointer address.

Example

Consider the example below:

packagemain
import (
    "fmt"
    "io"
    "os"
)
funcmain() {
    my_str:= "Hello world"
    str := fmt.Sprintf("The program say %s\n", my_str)
    io.WriteString(os.Stdout, str)
}

The example above uses the sprintf method to format the specified string. You can use other formatting specifiers to format other values.

Conclusion

This short article guides you to working with the sprintf function from the fmt package. Using this function, you can format strings in various ways using the specifiers discussed in this guide.

Thanks for reading.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list