golang

Console Printing in Go (Print to Console)

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:

import "fmt"

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:

fmt.Print("Hello, world!")

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.

fmt.Println("Hello, world!")

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.

name := "Matthew"
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:

x := 10
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("\ttab.")
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:

fmt.Print("Hello", "World")

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:

var name string
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:

value := 123
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:

import (
    "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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list