The most basic and first program that you will learn to create in any programming is printing a “Hello World” to the console. The role of this program is to show you the syntax of the language as well as depict the importance of console printing at the early stages.
Console printing plays a fundamental role in any language as it allows us to show the information, messages, and data to the console. This is the basis of advanced features such as user input and debugging.
In Go, we have an entire package dedicated to efficient and easy console printing operations. The “fmt” package comes packed with features and functions to aid in console printing.
In this tutorial, we will dive deep into the world of console printing using the Go programming language.
Console Printing Basics
To get started with console printing in Go, we need to start by importing the “fmt” package which contains all the useful functions and features for console printing.
We can import the “fmt” package by adding the following line:
This should provide us with printing the functions such as Print, Printf, Println, and more.
Basic Printing
The most basic way to print something to the console is using the “Print” function. An example is as follows:
In this example, we use the fmt.Print() function to display the “Hello, World!” string to the console.
One thing to note about the “Print” function is that it does not add a newline character at the end, so the cursor stays on the same line after printing.
Adding a New Line Character
To print a message and move to the next line, we can use the “Println” function. The “ln” means that the function adds a new line character at the end of the message.
The function appends a newline character (\n) at the end of the printed message, causing the cursor to move to the next line.
Formatted Text
If you are familiar with the C language, you are probably familiar with the “printf” function. In Go, we also access the “Printf” function which allows us to print the formatted text.
age := 78
fmt.Printf("Name: %s, Age: %d\n", name, age)
Using the “Printf” function allows us to include the placeholders such as “%s” and “%d” to format and print the value of the “name” and “age” variables within the string.
We also manually add a new line character at the end of the string.
Print Variables and Expressions
We can also directly print the variables and expressions using the “Print” or “Println” functions as shown in the following example:
y := 20
sum := x + y
fmt.Print("The sum of", x, "and", y, "is", sum)
fmt.Println("The sum is", sum)
In this example, we print the “x” and “y” variables and the result of sum using both “Print” and “Println”.
Format Specifier and Escape Sequences
In Go, we can format the console output with various escape sequences and modifiers.
1. Escape Sequences
Escape sequences are special characters that start with a backslash (\) and allows us to format the text. Some common escape sequences include:
- \n – Newline character
- \t – Tab character
- \\ – Print a literal backslash
- \” – Print a double quote
Example Usage:
fmt.Println("\nnew line.")
fmt.Println("backslash: \")
fmt.Println("double quote: "")
2. Format Specifiers
Format specifiers work well with the “Printf” function to specify how the values should be formatted. Common format specifiers include:
- %s – Format as a string
- %d – Format as a decimal (integer)
- %f – Format as a floating-point number
- %t – Format as a Boolean (true or false)
Print with Multiple Arguments
We can print multiple values in a single call to “Print”, “Println”, or “Printf” by separating them with commas. Go automatically inserts the spaces between the arguments as shown in the following example:
This prints “Hello World” with a space between the words.
Console Input
In addition to printing to the console, we can also read an input from the console using the “Scan” functions from the “fmt” package.
Consider the following example that demonstrate how to read an input from the use:
fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Printf("Hello, %s!\n", name)
Setting the Width and Precision
Go allows us to control the width and precision of printed values using the formatting specifiers.
For example, print an integer with a minimum width of 5 characters and a precision of 2 decimal places for a floating-point number:
pi := 3.14159265359
fmt.Printf("Value: %05d, Pi: %.2f\n", value, pi)
In this example, “%05d” ensures that the integer value is printed with a minimum width of 5 characters, zero-padded if necessary.
While “%.2f” specifies that the floating-point number of pi should be printed with two decimal places.
Console Print to Files
In addition to the standard console, we can redirect the output to a file using the OS package. This is useful for logging as shown in the following code example:
"fmt"
"os"
)
file, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
fmt.Fprintln(file, "write to file.")
In this example, we create a file named “output.txt” and use “fmt.Fprintln” to write the text to it.
Conclusion
In this tutorial, we walked you through everything you need to know to perform an efficient and pretty console printing using the Go programming language. Feel free to explore the docs on the “fmt” package to learn more.