Mastering Formatting Verbs in Go: Enhancing Printf() Precision

Mastering Formatting Verbs in Go: Enhancing Printf() Precision

Introduction

In Go programming, the Printf() function is a powerful tool for formatting and printing values. By using formatting verbs, you can control how your data is displayed, whether it's integers, strings, floats, or booleans. In this article, we'll explore the various formatting verbs available in Go's Printf() function, understand their usage, and see examples of how they work.

General Formatting Verbs

Go provides several general formatting verbs that can be used with all data types:

VerbDescription
%vPrints the value
%#vPrints in Go-syntax
%TPrints the type
%%Prints the percent sign
package main

import "fmt"

func main() {
  var i = 15.5
  var txt = "Hello World!"

  fmt.Printf("%v\n", i)
  fmt.Printf("%#v\n", i)
  fmt.Printf("%v%%\n", i)
  fmt.Printf("%T\n", i)

  fmt.Printf("%v\n", txt)
  fmt.Printf("%#v\n", txt)
  fmt.Printf("%T\n", txt)
}

Integer Formatting Verbs

For integer data types, Go offers several formatting verbs:

VerbDescription
%bBase 2
%dBase 10
%+dBase 10 with sign
%oBase 8
%OBase 8 with leading 0o
%xBase 16, lowercase
%XBase 16, uppercase
%#xBase 16 with leading 0x
%4dPad with spaces (width 4, right-justified)
%-4dPad with spaces (width 4, left-justified)
%04dPad with zeroes (width 4, zero-padded)
package main

import "fmt"

func main() {
  var i = 15

  fmt.Printf("%b\n", i)
  fmt.Printf("%d\n", i)
  fmt.Printf("%+d\n", i)
  fmt.Printf("%o\n", i)
  fmt.Printf("%O\n", i)
  fmt.Printf("%x\n", i)
  fmt.Printf("%X\n", i)
  fmt.Printf("%#x\n", i)
  fmt.Printf("%4d\n", i)
  fmt.Printf("%-4d\n", i)
  fmt.Printf("%04d\n", i)
}

String, Boolean, and Float Formatting Verbs

For other data types like strings, booleans, and floats, Go provides the following formatting verbs:

  • String:

    • %s: Prints as plain string

    • %q: Prints as a double-quoted string

    • %8s, %-8s: Prints as plain string with width (right/left-justified)

    • %x, % x: Prints as hex dump of byte values

  • Boolean:

    • %t: Prints in true or false format
  • Float:

    • %e: Scientific notation with 'e' as exponent

    • %f: Decimal point, no exponent

    • %.2f: Default width, precision 2

    • %6.2f: Width 6, precision 2

    • %g: Exponent as needed, only necessary digits

// Example for string, boolean, and float formatting verbs

Conclusion

Formatting verbs in Go's Printf() function provide precise control over how data is displayed. By selecting the appropriate verb for each data type, you can ensure your output is formatted correctly and easy to read. Whether you're printing integers, strings, floats, or booleans, Go's rich set of formatting verbs offers flexibility and precision in displaying your data. Happy coding!