Go - Fmt Package



The fmt package is one of the most commonly used packages in GoLang. It is used for formatting text and printing it to standard output or to a file. This package is part of the Go standard library, and it is included with every Go installation. In this article, we will explore the fmt package and learn how to use it effectively in our Go programs.

What is the fmt Package?

The fmt package is a built-in package in GoLang that provides functions for formatting text and printing it to the console or to a file. It includes a wide variety of functions for formatting strings, numbers, and other types of data.

Functions in the fmt Package

The fmt package includes several functions that can be used for formatting and printing text. Some of the most commonly used functions are

  • fmt.Print() This function is used to print text to the console.
  • fmt.Printf() This function is used to format text and print it to the console.
  • fmt.Println() This function is used to print text to the console, followed by a new line character.
  • fmt.Sprintf() This function is used to format text and return it as a string.

There are also other functions available in the fmt package that can be used for more specialized formatting, such as

  • fmt.Errorf() This function is used to create an error message with formatted text.
  • fmt.Scan() This function is used to scan input from the console and parse it into different types of data.
  • fmt.Scanln() This function reads user input until a newline is encountered.
  • fmt.Sscanf() This function scans input from a string instead of the console.
  • fmt.Sprint() This function is used to format data as a string and return it.

Using the fmt Package

To use the fmt package in your Go program, you need to import it at the beginning of your file

import "fmt"

Once you have imported the package, you can use the various functions available in it. Here are some examples of how to use the fmt package

Use of fmt package

The fmt package is widely used in Go programs for printing and formatting text efficiently.

Example

In the following example, we are demonstrating basic usage of the fmt package for printing and formatting text.

package main

import "fmt"

func main() {
   // Declare a variable
   x := 42
   
   // Printing a string to the console
   fmt.Print("Hello, world! \n")
   
   // Printing a formatted string to the console
   fmt.Printf("The value of x is %d \n", x)
   
   // Printing a string to the console with a new line character
   fmt.Println("This is a new line")
   
   // Formatting data as a string and returning it
   result := fmt.Sprintf("The value of x is %d ", x)
   fmt.Println(result)
}

When the above code is compiled and executed, it produces the following result −

Hello, world! 
The value of x is 42 
This is a new line
The value of x is 42 

Reading Input using fmt.Scan()

The fmt.Scan() function reads user input from the console and assigns it to variables.

Example

In the following example, we are using fmt.Scan() to read a user's name and print a greeting message.

package main

import "fmt"

func main() {
   var name string
   fmt.Print("Enter your name: ")
   fmt.Scan(&name)
   fmt.Println("Hello,", name)
}

When the above code is compiled and executed, it produces the following result −

Enter your name: John
Hello, John

Reading Input using fmt.Scanln()

The fmt.Scanln() function reads input until the user presses enter.

Example

In the following example, we are using fmt.Scanln() to read a user's full name and print a greeting message.

package main

import "fmt"

func main() {
   var name string
   fmt.Print("Enter your full name: ")
   fmt.Scanln(&name)
   fmt.Println("Hello,", name)
}

Using fmt.Sprintf() for String Formatting

The fmt.Sprintf() function formats text and returns it as a string.

Example

In the following example, we are using fmt.Sprintf() to format a string with numerical values.

package main

import "fmt"

func main() {
   var a, b int = 10, 20
   result := fmt.Sprintf("Sum of %d and %d is %d", a, b, a+b)
   fmt.Println(result)
}

When the above code is compiled and executed, it produces the following result −

Sum of 10 and 20 is 30

Using fmt.Errorf() for Error Messages

The fmt.Errorf() function creates formatted error messages.

Example

In the following example, we are using fmt.Errorf() to generate an error message when attempting to divide by zero.

package main

import (
   "errors"
   "fmt"
)

func divide(a, b int) (int, error) {
   if b == 0 {
      return 0, fmt.Errorf("cannot divide by zero")
   }
   return a / b, nil
}

func main() {
   result, err := divide(10, 0)
   if err != nil {
      fmt.Println("Error:", err)
   } else {
      fmt.Println("Result:", result)
   }
}

When the above code is compiled and executed, it produces the following result −

Error: cannot divide by zero
Advertisements