Introduction
One of my New Year’s resolutions was to blog at least once a week. Yea…that’s working out pretty well so far. I kind of fell behind with blogging as I have been trying to cram Kubernetes and Go down my throat as quickly as possible. Kubernetes is like a monster all on its own and I feel like right when I think I am getting it, there are 50 new things to learn. I’m OK with knowing I will likely not ever know everything, if I did, I’d be bored.
I have been trying to split my time between Go and Kubernetes. I’ve been learning some fun things in Go such as formatting print statements. As I was learning Go, I was always using Println until I learned more about Printf. Printf has a lot more formatting options and I feel like the more I use it, the easier it is.
Printf vs Println
Printf – Print formatter. Prints formatted strings. You can use symbols in the string to specify how you want to print arguments at the specified points. Printf does not add a new line at the end of a statement link Println, so you will need to add a “\n” to insert a new line.
Println – Print line. Inserts a new line at the end of a statment and formats the string using the default formats for it’s operands.
Let’s look at a few examples.
package main
import "fmt"
func main() {
var myName = "Fritzie"
fmt.Printf("%q\n", myName)
}
This prints: “Fritzie”
First we import the fmt package. Then we create a variable called myName and then print it. The %q prints a string that is quoted. If you had used %s, the string would just print as: Fritzie. The \n is an escape sequence and it prints a new line after printing Fritzie. myName is the replacer value that replaces the verb inside the formatting text (the %q).
Let’s compare a Printf statement with Println…
We want to print the following:
Total: 100.5 Passed: 20 / Failed 80.5
With Println, this would look like:
package main
import (
"fmt"
)
func main() {
var (
total = 100.50
pass = 20
fail = 80.5
)
fmt.Println("Total:", total, "Passed:", pass, "/", "Failed", fail)
}
With Printf, this would look like:
package main
import (
"fmt"
)
func main() {
var (
total = 100.50
pass = 20
fail = 80.5
)
fmt.Printf("Total: %.2f Passed: %d / Failed %.1f\n", total, pass, fail)
}
Here, you use %.2f to represent a float with precision of 2 decimal places. The %d represents an integer and %.1f is another floating point number with a precision of 1 decimal place. The \n escape sequence adds a new line. Finally, we pass in total, pass, and fail to replace the verbs with our values.
Conclusion
We learned about the differences between Printf and Println in Go. Which do you think is easier to read or to use?
Additional Resources
Cheat sheet for Printf specifiers: https://alvinalexander.com/programming/printf-format-cheat-sheet/