What are other format verbs?

In Go, the fmt package provides several format verbs that you can use with functions like Printf, Sprintf, and Fprintf to format different types of data. Here’s a list of some common format verbs along with their descriptions:

Common Format Verbs

  1. %s:

    • Formats a string.
    • Example: fmt.Printf("Hello, %s!", "Alice")Hello, Alice!
  2. %d:

    • Formats an integer in base 10.
    • Example: fmt.Printf("Age: %d", 30)Age: 30
  3. %f:

    • Formats a floating-point number in decimal notation.
    • Example: fmt.Printf("Height: %f", 5.6)Height: 5.600000
  4. %.2f:

    • Formats a floating-point number with two decimal places.
    • Example: fmt.Printf("Height: %.2f", 5.6)Height: 5.60
  5. %v:

    • Formats the value in a default format. It works for any type.
    • Example: fmt.Printf("Value: %v", []int{1, 2, 3})Value: [1 2 3]
  6. %T:

    • Formats the type of the value.
    • Example: fmt.Printf("Type: %T", 42)Type: int
  7. %p:

    • Formats a pointer in hexadecimal notation.
    • Example:
      var ptr *int
      fmt.Printf("Pointer: %p", ptr) // Output will be the address of ptr
  8. %x:

    • Formats an integer in hexadecimal notation.
    • Example: fmt.Printf("Hex: %x", 255)Hex: ff
  9. %b:

    • Formats an integer in binary notation.
    • Example: fmt.Printf("Binary: %b", 5)Binary: 101
  10. %o:

    • Formats an integer in octal notation.
    • Example: fmt.Printf("Octal: %o", 8)Octal: 10
  11. %c:

    • Formats a character represented by a Unicode code point.
    • Example: fmt.Printf("Character: %c", 65)Character: A
  12. %q:

    • Formats a string as a double-quoted string.
    • Example: fmt.Printf("Quoted: %q", "Hello")Quoted: "Hello"

Example Usage

Here’s a quick example that demonstrates several of these format verbs:

package main

import "fmt"

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

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
    fmt.Printf("Height: %.1f feet\n", height)
    fmt.Printf("Score: %.2f\n", score)
    fmt.Printf("Binary of Age: %b\n", age)
    fmt.Printf("Hex of Score: %x\n", int(score))
}

Conclusion

These format verbs provide a powerful way to control the output format of various data types in Go. By using them effectively, you can create clear and informative output for your applications. If you have any further questions or need more examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!