Want to learn how to build better Go applications faster and easier? You can.
Check out my course on the Go Standard Library. You can check it out now for free.
Hey there, fellow developers! Today, we’re going to talk about one of the most basic, yet essential, functions in programming - printing. And what better language to explore this topic with than Go? In this article, we’ll show you how to print in Go, and demonstrate some of the useful features that make Go’s printing capabilities stand out. So, let’s get started!
The simplest way to print in Go is by using the fmt.Println()
function. This function takes any number of arguments of any type and prints them to the console, separated by spaces. Here’s an example:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
If you run this file, it looks like this:
This code will output the string “Hello, world!” to the console. Easy, right?
But what if we want to print something more complex, like a formatted string? For that, we can use Go’s string formatting capabilities. Let’s say we want to print a string that includes a variable. We can use the %v placeholder to print the value of the variable. Here’s an example:
package main
import "fmt"
func main() {
name := "Fred"
fmt.Printf("Hello, %v!\n", name)
}
This code will output “Hello, Fred!” to the console.
We used the Printf()
function from the fmt
package to format the string, and used the %v
placeholder to include the value of the name variable in the string.
But that’s not all! Go’s string formatting capabilities are extensive, and include placeholders for various types, as well as control over the formatting of numbers, dates, and more. Here’s an example that demonstrates some of these features:
package main
import "fmt"
func main() {
age := 35
height := 1.8
birthdate := "1987-05-17"
fmt.Printf("I am %d years old, %g meters tall, and my birthdate is %v.\n", age, height, birthdate)
}
This code will output “I am 35 years old, 1.8 meters tall, and my birthdate is 1987-05-17.” to the console. We used the %d placeholder for integers, %g for floating point numbers, and %v for strings.
We also included the format for the birthdate using the 2006-01-02 placeholder, which is a special date format that Go uses.
Printing in Go is simple and powerful, with a variety of options for formatting strings and printing different types of data. Whether you’re just starting out with Go, or are a seasoned developer, knowing how to print in Go is an essential skill that you’ll use every day. So, give it a try and start printing with Go today!