What are common format specifiers?

Here are some common format specifiers used in Go's Printf function:

Common Format Specifiers:

  1. String and Character:

    • %s - Formats a string.
    • %q - Formats a string as a double-quoted string (with escape characters).
    • %c - Formats a single character (rune).
  2. Integer:

    • %d - Formats a decimal integer.
    • %b - Formats an integer in binary representation.
    • %o - Formats an integer in octal representation.
    • %x - Formats an integer in hexadecimal (lowercase).
    • %X - Formats an integer in hexadecimal (uppercase).
  3. Floating-Point:

    • %f - Formats a floating-point number in decimal notation.
    • %e - Formats a floating-point number in scientific notation (lowercase).
    • %E - Formats a floating-point number in scientific notation (uppercase).
    • %g - Formats a floating-point number using the shortest representation between %f and %e.
  4. Boolean:

    • %t - Formats a boolean value (true or false).
  5. Pointer:

    • %p - Formats a pointer address in hexadecimal.
  6. Default Format:

    • %v - Formats the value in its default format.
    • %+v - Formats a struct with field names.
    • %#v - Formats the value in Go-syntax representation.
  7. Width and Precision:

    • %5d - Right-aligns an integer with a width of 5.
    • %-5s - Left-aligns a string with a width of 5.
    • %10.2f - Formats a floating-point number with a width of 10 and 2 decimal places.

Example Usage:

package main

import "fmt"

func main() {
    name := "Alice"
    age := 30
    height := 5.6

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
    fmt.Printf("Height: %.1f\n", height)
}

Output:

Name: Alice
Age: 30
Height: 5.6

These format specifiers provide flexibility in how you present data in your Go programs.

0 Comments

no data
Be the first to share your comment!