golang

Learn How to print in console in Golang


In this article, you are going to learn about how to print in console in the Go language.

Print data in the console is a part and parcel of a programmer’s life. While writing code for a specific program, you often need to see whether the code is running perfectly or not before launching it to the production level. To do so you need to print your program code in the console and if there’s any complication you may easily debug it.

Like other programming languages, the Go language has the functionality of printing data in the console. It provides the functionality with the help of two functions – Println() and Printf(). Both of these functions are available in the fmt package of Go. Let’s see how you can print data in the console with the help of Println() function first:

package main

import (
        "fmt"
)

func main() {

        // Printing a String
        fmt.Println("Good Morning!")

        // Printing a Integer
        fmt.Println(21)

}

/*
      Output:
        Good morning!
        21
*/

Here, first, we have imported the fmt package as we know that Println() function is available in the fmt package. The moment we have written something inside the Println() function that is valid in the Go language, it simply Prints all the arguments to console output. If you have more than one argument to print then it separates the argument with space for you. Let’s see an example for it:

package main

import (
        "fmt"
)

func main() {

        // Printing Multiple Strings
        fmt.Println("Good Morning!", "Good Noon!", "Good Night!")

        // Printing Multiple Integers
        fmt.Println(21, 31, 41, 51)

}

/*
      Output:
        Good Morning! Good Noon! Good Night!
        21 31 41 51
*/

There is another function that is also provided by the fmt package in the Go language is Printf(). Now you may ask that, we can print data to the console with the help of Println() function then why Go provide Printf() function. The main reason behind it is to fulfill the need of printing a formatted string to the console. See the below code example to get a clear understanding:

package main

import (
        "fmt"
)

func main() {

        name, age, cgpa := "Deven", 23, 3.70

        //Using Println()
        fmt.Println("Name =", name, "Age =", age, "CGPA =", cgpa)

        //Using Printf()
        fmt.Printf("Name = %s, Age = %d, CGPA = %0.2f", name, age, cgpa)

}

/*
      Output:
        Name = Deven Age = 23 CGPA = 3.7
        Name = Deven, Age = 23, CGPA = 3.70
*/

Here, you can see that in the floating number we didn’t get the exact value while we are using Println() function but we got it in Printf() function. In the Go language, both functions are used to print data in the console and both have different uses based on some specific priorities.


Share on social media

//