What are other format specifiers?

In Go, Printf supports a variety of format specifiers that allow you to control how different types of data are displayed. Here are some commonly used format specifiers:

Common Format Specifiers:

  1. String and Character:

    • %s - String
    • %q - Double-quoted string (with escape characters)
    • %c - Character (rune)
  2. Integer:

    • %d - Decimal integer
    • %b - Binary representation
    • %o - Octal representation
    • %x - Hexadecimal representation (lowercase)
    • %X - Hexadecimal representation (uppercase)
  3. Floating-Point:

    • %f - Decimal point and exponent (default)
    • %e - Scientific notation (lowercase)
    • %E - Scientific notation (uppercase)
    • %g - Uses the shortest representation between %f and %e
    • %.nf - Floating-point with n decimal places (e.g., %.2f for two decimal places)
  4. Boolean:

    • %t - Boolean (true or false)
  5. Pointer:

    • %p - Pointer address in hexadecimal
  6. Default Format:

    • %v - Default format for the value
    • %+v - Struct with field names
    • %#v - Go-syntax representation of the value
  7. Width and Precision:

    • %5d - Right-aligned integer with a width of 5
    • %-5s - Left-aligned string with a width of 5
    • %10.2f - 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
    isStudent := true

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

Output:

Name: Alice
Age: 30
Height: 5.6
Is Student: true

Feel free to experiment with these format specifiers to see how they affect the output!

0 Comments

no data
Be the first to share your comment!