The fmt package in Golang

In multiple stages of a program, we need to print values or other data or we may need to log various data for debugging. This type of basic debugging helps us write better code. The fmt package supports various format specifiers for printing. In this post, we are going to discuss the fmt package in Golang.

Required imports for fmt package

The functions we will be discussing here are from the fmt package, so we need to import it. We will also be producing output to the standard console, so we are going to use the os package as well.

import (
    "fmt"
    "os"
)

The functions available in fmt package

The package consists of mainly reading and writing functions equipped with the string formatting support. Here are the most common variadic functions which are available in the package.

  • Fprint, Fprintf & Fprintln
  • Fscan, Fscanf & Fscanln
  • Sprint, Sprintf & Sprintln
  • Sscan, Sscanf & Sscanln

It may seem confusing but it will be a bit easier after using some of them. Here are some ways of distinguishing them.

All functions starting with F writes or reads the string to or from the stream provided as its argument. The argument must implement io.Writer or io.Reader interface depending on the use case.

All functions which start with S returns the string it created using the format specifiers. It doesn’t print items automatically.

The functions which end with ln such as Fprintln or Fscanln adds a newline.

The functions with an f at the ends support formatting.

Golang fmt package print functions

Most of the functions that the package has are variadic functions, which means it can take any number of arguments depending on the usage of the function. Here are some of the functions in use.

package main

import (
	"fmt"
	"os"
)

func main() {

	v := 42

	// Spaces are to be added manually
	fmt.Print("This", "is", "a", 42, "string\n")        // Thisisa42string  
	
	fmt.Println("Another", "string")                    // Another string
	
	fmt.Printf("The value is %d\n", v)                  // The value is 42  // formatting support
	
	s := "formatted"
	
	// Spaces are to be added manually
	// os.Stdout is an io.Writer
	fmt.Fprint(os.Stdout, "Yet", "another", "string\n") // Yetanotherstring
	fmt.Fprintln(os.Stdout, "A", "string")              // A string
	fmt.Fprintf(os.Stdout, "A %s string\n", s)          // A formatted string
}

Golang fmt package scan functions

The scan functions are used to take values from the standard input. Here are some of them in action.

package main

import (
    "fmt"
)

func main() {
      var a, b int

      // use address-of operator to get the values into the variable
      fmt.Scan(&a, &b)

      // print the values taken
      fmt.Println(a, b)
}
Scan Numbers In Go
Scan Numbers In Go

The Scanln function can be used in the same way as shown below.

package main

import (
    "fmt"
)

func main() {
      var a, b int

      // use address-of operator to get the values into the variable
      fmt.Scanln(&a, &b)
      fmt.Println(a, b)
}
Scanln Function In Go
Scanln Function In Go

The functions with the S in front of them does the same, the only difference is they don’t print data instead they return the string.

The stringer interface in fmt package

The stringer interface implementor can simply be passed to a print function as an argument and it will print in the way it is defined.

Here is an example of a struct that implements the stringer interface.

package main

import (
	"fmt"
)

// define a struct
type Book struct{
	Name string
	Author string
}

// implement the stringer interface by
// implementing the String() string function
func (b Book)String() string {
	return fmt.Sprintf("%s was written by %s\n", b.Name, b.Author)
}

func main() {
	b := Book{
		"1984",
		"George Orwell",
	}
	
        // pass as argument directly
	fmt.Println(b)                // 1984 was written by George Orwell
}

As can be seen, there is a multitude of useful functions and types are provided by the fmt package as it is one of the most essential packages in Go.