Fmt Package in GoLang


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.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 −

Example

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)
}

Output

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

Conclusion

The fmt package is an essential part of the GoLang standard library. It provides a wide variety of functions for formatting text and printing it to the console or to a file. By using the fmt package, you can make your Go programs more readable and easier to understand. We hope that this article has provided you with a good understanding of the fmt package and how to use it effectively in your Go programs.

Updated on: 18-Apr-2023

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements