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
-
%s:
- Formats a string.
- Example:
fmt.Printf("Hello, %s!", "Alice")→Hello, Alice!
-
%d:
- Formats an integer in base 10.
- Example:
fmt.Printf("Age: %d", 30)→Age: 30
-
%f:
- Formats a floating-point number in decimal notation.
- Example:
fmt.Printf("Height: %f", 5.6)→Height: 5.600000
-
%.2f:
- Formats a floating-point number with two decimal places.
- Example:
fmt.Printf("Height: %.2f", 5.6)→Height: 5.60
-
%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]
-
%T:
- Formats the type of the value.
- Example:
fmt.Printf("Type: %T", 42)→Type: int
-
%p:
- Formats a pointer in hexadecimal notation.
- Example:
var ptr *int fmt.Printf("Pointer: %p", ptr) // Output will be the address of ptr
-
%x:
- Formats an integer in hexadecimal notation.
- Example:
fmt.Printf("Hex: %x", 255)→Hex: ff
-
%b:
- Formats an integer in binary notation.
- Example:
fmt.Printf("Binary: %b", 5)→Binary: 101
-
%o:
- Formats an integer in octal notation.
- Example:
fmt.Printf("Octal: %o", 8)→Octal: 10
-
%c:
- Formats a character represented by a Unicode code point.
- Example:
fmt.Printf("Character: %c", 65)→Character: A
-
%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!
