DEV Community

Emil Ossola
Emil Ossola

Posted on

Printing in Go with the Print and Printf Functions

Printing is the most basic way of displaying information on a computer screen. In Go, printing is done through the fmt package, which is part of the standard library. The fmt package provides two main functions for printing: Print() and Printf().

The Print() function simply prints the text on the screen, while Printf() allows us to format the text before printing. The format string in Printf() can contain placeholders, which will be replaced with the values provided as arguments. These placeholders start with a percent sign (%), and the letter after the percent sign indicates the type of value to be replaced.

The Print() and Printf() functions also accept multiple arguments, which are printed separated by spaces.

In this article, we will explain the importance of printing in programming and how Go provides two built-in functions, Print and Printf, for this purpose. We will also go on to explain the differences between the two functions and how they can be used to output strings, numbers, and variables.

Image description

Using the Print Function

The Print function in Go is a built-in function that allows you to print to the standard output (usually the console). The Print function takes zero or more arguments of any type and concatenates them into a string using spaces as separators, and then writes the resulting string to the standard output.

If you want to use a different separator, you can use the Println function instead, which uses a newline character as the separator. The Print function is useful for quickly printing a value or a set of values to the console for debugging purposes. Here is an example of the Print function in action:

package main

import "fmt"

func main() {
    fmt.Print("Hello", " ", "World") // prints "Hello World"
}
Enter fullscreen mode Exit fullscreen mode

In this example, we use the Print function to print the string "Hello World" to the console. The function concatenates the three string arguments into a single string separated by a space character and then writes the resulting string to the console.

Syntax of the Print function

The Print function in Go is used to print text to the standard output stream (usually the console). It can be called with a series of arguments, each separated by a comma. The function takes care of converting the arguments to their string representation and concatenating them together before printing them out. The basic syntax of the Print function is as follows:

func Print(a ...interface{}) (n int, err error)
Enter fullscreen mode Exit fullscreen mode

The a argument is a variadic parameter, which means that it can take any number of arguments. The function returns the number of bytes written to the output stream and any error that occurred during the process. The arguments can be of any type that has a string representation, including strings, integers, floats, and boolean values.

Printing an Integer

Printing an integer value in Go is quite simple. The Print and Printf functions from the fmt package can be used to print integer values. The Print function prints the integer in its decimal representation, while the Printf function allows for more control over the output format. Here is an example that demonstrates how to print an integer using both functions:

package main

import "fmt"

func main() {
    num := 42

    // Using Print
    fmt.Print(num) // Output: 42

    // Using Printf
    fmt.Printf("The number is %d.\n", num) // Output: The number is 42.
}
Enter fullscreen mode Exit fullscreen mode

In this example, we first define an integer variable num with a value of 42. We then use the Print function to print the value of num on its own line. Next, we use the Printf function to print the value of num in a sentence, which includes the literal string "The number is " and the integer value of num using the %d format specifier. The resulting output is "The number is 42.".

Printing Multiple Variables

You can also print multiple variables using the Printf() function. This function allows you to format your output in a specific way. You can insert values into the output string by using format verbs. The %v verb represents the value of the variable being printed. You can use the %v verb more than once to print multiple variables. Here is an example of how to print multiple variables using Printf():

age := 25
name := "John"
fmt.Printf("My name is %v and I am %v years old.", name, age)
Enter fullscreen mode Exit fullscreen mode

Output: My name is John and I am 25 years old.

In the example above, we declare two variables age and name. We then use Printf() to print them as part of a sentence. The %v verb is used to represent the value of the variables name and age. The variables are passed to Printf() as arguments in the order that they should appear in the output string.

Differences between Print and Println functions

In Go, the Print and Println functions are used to print output to the console. The main difference between them is that Println adds a newline character at the end of the output, while Print does not. This means that if you use Println to print multiple values, each value will be printed on a new line.

On the other hand, if you use Print, all the values will be printed on the same line, separated by a space character. Additionally, Println also accepts multiple arguments, separated by a comma, while Print only accepts a single argument.

The Print and Println functions in Go have a subtle difference in how they handle the output.

Print

  • The Print function formats the output without adding a new line character (\n) at the end.
  • If multiple arguments are provided, they are concatenated without any spacing between them.
fmt.Print("Hello", "World")
// Output: HelloWorld
Enter fullscreen mode Exit fullscreen mode

Println

  • The Println function adds a new line character (\n) at the end of the output.
  • If multiple arguments are provided, they are separated by a space and a new line character is appended at the end.
fmt.Println("Hello", "World")
// Output:
// Hello World
Enter fullscreen mode Exit fullscreen mode

It's important to note that both Print and Println functions automatically convert different data types to their string representations when printing.

Using the Printf Function

The Printf function in Go is used to format and print text on the console or terminal. It takes a format string as its first argument, which specifies the layout of the output string, and any additional arguments are used to fill in the placeholders in the format string.

The format string can contain various placeholders, such as %s for strings, %d for integers, %f for floating-point numbers, and many more. The function replaces these placeholders with the corresponding values of the additional arguments, according to their order. The Printf function also supports various modifiers and flags to control the output's alignment, precision, width, and other properties.

Syntax of the Printf function

The Printf function is a formatted output function that is used to print values in a specific format. The syntax of the Printf function is quite simple. It starts with the letter f that stands for formatted. It is followed by the letter printf, which is the name of the function.

The format string is enclosed in double quotes "" and it contains the text to be printed along with any placeholders or format specifiers. The placeholders are marked with the percent symbol %, and they are replaced with the values of variables that are passed to the function. The format specifiers are used to specify the type of data that is being printed and how it should be formatted.

func Printf(format string, a ...interface{}) (n int, err error)

Printing string with formatting

In Go, we can use the Printf() function to print formatted strings. The function takes a format string as its first argument, followed by any number of arguments that will replace the format specifiers in the format string.

The format string is composed of two types of elements: literal text and format specifiers. Literal text is printed as is, while format specifiers are placeholders for values that will be printed in a specific format. For example, the %s format specifier is used to print strings, while the %d format specifier is used to print integers. Let's see an example:

name := "John"
age := 30
fmt.Printf("My name is %s and I'm %d years old.\n", name, age)
Enter fullscreen mode Exit fullscreen mode

This will output My name is John and I'm 30 years old. to the console.

Printing integers with formatting

Go provides a powerful formatting syntax that allows us to print integers in various formats. We can use the %d verb to print an integer in decimal format. For example, if we have an integer variable num and we want to print it, we can use the Printf() function as follows:

num := 42
fmt.Printf("The value of num is %d\n", num)
Enter fullscreen mode Exit fullscreen mode

This will print The value of num is 42 to the console. We can also use the %x verb to print an integer in hexadecimal format, or the %o verb to print an integer in octal format. Additionally, we can use the %b verb to print an integer in binary format. We can also specify the width and precision of the output using the formatting syntax. For example, we can print an integer with a minimum width of 5 digits as follows:

num := 42
fmt.Printf("The value of num is %05d\n", num)
Enter fullscreen mode Exit fullscreen mode

This will print The value of num is 00042 to the console. We can also print integers in different bases using the strconv package.

Printing floating-point numbers with formatting

Printing floating-point numbers is a common task in programming. In Go, we can use the Printf function to print floating-point numbers with specific formatting options. The Printf function uses the %f verb to print floating-point numbers. For example, if we have a variable num that stores a floating-point number, we can print it with two decimal places using the following code:

num := 3.14159
fmt.Printf("The value of num is %.2f\n", num)
Enter fullscreen mode Exit fullscreen mode

This will output:

The value of num is 3.14
Enter fullscreen mode Exit fullscreen mode

In addition to the decimal places, we can also specify other formatting options such as the width of the field and whether to use scientific notation. The Printf function provides a powerful way to format and print floating-point numbers in Go.

Printing multiple variables with formatting

In Go, we can print multiple variables in a single line using the Printf() function. This function allows us to format the output string using special formatting verbs. For example, we can use %s to format a string, %d to format an integer, %f to format a float, and so on.

To print multiple variables, we just need to pass them as additional arguments to the Printf() function, separated by commas. We can use the same formatting verbs for each variable and specify the order in which they appear in the output string by using numbered placeholders. For example:

name := "John"
age := 30
height := 1.75

fmt.Printf("Name: %s, Age: %d, Height: %.2f\n", name, age, height)
Enter fullscreen mode Exit fullscreen mode

This will output:

Name: John, Age: 30, Height: 1.75
Enter fullscreen mode Exit fullscreen mode

In the format string, we used %s to format the string variable name, %d to format the integer variable age, and %f with a precision of 2 to format the float variable height. We also used numbered placeholders (%1$s, %2$d, %3$.2f) to specify the order in which the variables appear in the output string.

Commonly used formatting verbs in Printf funct

The Printf function in Go is indeed used for printing formatted output to the standard output stream. It allows you to control the format of the output by using formatting verbs in the format string. Formatting verbs are placeholders that specify the type and format of the data that will be printed.

Here are some commonly used formatting verbs:

Image description

By using these formatting verbs along with the corresponding arguments, you can control the output format and ensure that the data is displayed as desired. Understanding the usage of formatting verbs is important for achieving the desired output format when using the Printf function in Go.

Print Type in Golang

In Go, you can print the type of a variable using the %T formatting verb in the Printf function from the fmt package. Here's an example:

package main

import "fmt"

func main() {
    var num int
    var str string
    var flag bool

    fmt.Printf("Type of num: %T\n", num)
    fmt.Printf("Type of str: %T\n", str)
    fmt.Printf("Type of flag: %T\n", flag)
}
Enter fullscreen mode Exit fullscreen mode

Output:

Type of num: int
Type of str: string
Type of flag: bool
Enter fullscreen mode Exit fullscreen mode

In the example, the %T formatting verb is used to print the type of the variables num, str, and flag. The output shows the respective types: int, string, and bool.

Print Struct in Golang

To print the contents of a struct in Go, you can use the %v formatting verb in the Printf function from the fmt package. Here's an example:

package main

import "fmt"

type Person struct {
    Name    string
    Age     int
    Country string
}

func main() {
    person := Person{
        Name:    "John Doe",
        Age:     30,
        Country: "USA",
    }

    fmt.Printf("%v\n", person)
}
Enter fullscreen mode Exit fullscreen mode

Output:

{John Doe 30 USA}
Enter fullscreen mode Exit fullscreen mode

In the example, the %v formatting verb is used to print the contents of the person struct. It prints all the fields of the struct, separated by spaces, enclosed within curly braces. The output shows the values of the Name, Age, and Country fields of the person struct.

Learn Go Programming with Go Online Compiler

Are you having trouble dealing with errors and debugging when coding? Don't worry, because conquering them is way easier than scaling Mount Everest!

Introducing Lightly IDE, your ultimate coding companion that transforms the learning curve into a thrilling adventure. With Lightly IDE, you don't have to be a coding genius to program smoothly. Discover the wonders of Lightly IDE at lightly-dev.com today!

Image description

Lightly IDE is truly remarkable, especially with its seamless integration of artificial intelligence (AI). This means that even if you're not a tech whiz, you can effortlessly navigate and utilize all its features. It's like having a magical power at your fingertips, but instead of wands, you're wielding lines of code.

If you're curious about programming or eager to enhance your skills, Lightly IDE provides the perfect entry point. With its Go online compiler, it's like stepping into a playground designed for aspiring programming prodigies. This platform has the incredible ability to transform a complete beginner into a coding expert in no time at all.

Read more: Printing in Go with the Print and Printf Functions

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.