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:
Verb | Description |
%v | Prints the value |
%#v | Prints in Go-syntax |
%T | Prints 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:
Verb | Description |
%b | Base 2 |
%d | Base 10 |
%+d | Base 10 with sign |
%o | Base 8 |
%O | Base 8 with leading 0o |
%x | Base 16, lowercase |
%X | Base 16, uppercase |
%#x | Base 16 with leading 0x |
%4d | Pad with spaces (width 4, right-justified) |
%-4d | Pad with spaces (width 4, left-justified) |
%04d | Pad 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!