Exploring the Go fmt package

robogeek95

Azeez Lukman

Posted on August 22, 2021

Exploring the Go fmt package

fmt is pronounced “fumpt” is one of Go’s core packages. It's mainly used for printing information to the terminal. fmt package has a broader purpose like helping us format data, for this reason, it's sometimes referred to as the format package.

Functions in Go fmt package:

The package three set of functions based on their usage

  • Functions used to format and print data in various ways and use cases:

    • Println()
    • Print()
    • Printf()
  • Functionsthat only formats the data and prints nothing

    • Sprint()
    • Sprintln()
    • Sprintf()
  • And a Functions to read user input from the terminal

    • Scan()

Functions used to format and print data in various ways and use cases

The Go fmt package gives two closely-related functions for formatting a string to be displayed on the terminal.

.Print()

When the arguments are strings, it concatenates them without any spacing and prints the result to the console.

fmt.Print("My", "name", "is", "Lukman")

// MynameisLukman
Enter fullscreen mode Exit fullscreen mode

When none of the arguements is a string, the Print function adds spaces between them.

fmt.Print(10, 20)

// 10 20

Enter fullscreen mode Exit fullscreen mode

.Println()

on the other hand always adds a space between its arguements and appends a new line or a line break at the end

fmt.Println("My", "name", "is", "Lukman")

fmt.Println("new", "line")

// My name is Lukman
// new line

Enter fullscreen mode Exit fullscreen mode

.Printf()

The Go.Printf() function in fmt provides custom formatting of a string using one or more verbs. A verb is a placeholder for a named value (constant or variable) to be formatted according to these conventions:

  • %v represents the named value in its default format
  • %d expects the named value to be an integer type
  • %f expects the named value to be a float type
  • %T represents the type for the named value

but unlike .Println(), .Printf() does not append a newline to the formatted string.

name := "Lukman"
fmt.Printf("My name is %v", name)
// My name is Lukman

age := 90
fmt.Printf("I am %d years old", age)
// I am 90 years old
Enter fullscreen mode Exit fullscreen mode

Functions that only formats the data and prints nothing

Unlike the .Print() and .Println() functions, the fmt package provides other functions that don’t print strings, but format them instead: The fmt.Sprint() and fmt.Sprintln().

fmt.Sprint()

user := "Kenny"
Feedback := "Nice book!"
userFeedback := fmt.Sprint(user, "feedback on your book is", feedback)


fmt.Print(userFeedback)
// Prints: Kenny feedback on your book is Nice book!
Enter fullscreen mode Exit fullscreen mode

Take a closer look at userFeedback and how calling fmt.Sprint() doesn’t print out anything. Rather, it returned a value that we store in userFeedback. When a value is returned, it means that a function did some computation and is giving back the computed value. Afterward, we can use the returned value for later usage. we’ve formatted one string by concatenating four separate strings. To see the value of userFeedback, we have to use a print statement.

fmt.Sprintln()

fmt.Sprintln() works like fmt.Sprint() but it automatically includes spaces between the arguments for us (just like fmt.Println() and fmt.Print()):

quote = fmt.Sprintln("see here,", "no spaces!")
fmt.Print(quote) // Prints see here, no spaces!
Even though we didnt add a trailing space in "see here," or a leading space in "no spaces!", quote is concatenated with a space in between: "see here,", "no spaces!".
Enter fullscreen mode Exit fullscreen mode

The Sprintf function

when we have to interpolate a string, without printing it, then we can use fmt.Sprintf().

Just like fmt.Printf(), fmt.Sprintf() can also use verbs:

user := "userA"
winner := fmt.Sprintf("The winner is… %v!", user)

fmt.Print(answer) // Prints: The winner is is… userA!
Enter fullscreen mode Exit fullscreen mode

fmt.Sprintf() works very similarly to fmt.Printf(), the major difference is that fmt.Sprintf() returns its value instead of printing it out!

Function for reading user input

The Go fmt .Scan() function scans user input from the terminal and extracts text delimited by spaces into successive arguments. A newline is considered a space. This function expects an address of each argument to be passed.

package main
import "fmt"

func main() {
var name string
var age int
fmt.Println("What's your name?")
fmt.Scan(&name)

fmt.Println("and what's your age?")
fmt.Scan(&age)

fmt.Printf("%v is %d years old!", name, age)
}


//$ What's your name?
//$ Lukman
//$ now what's your age?
//$ 90
//$ Lukman is 90 years old!
Enter fullscreen mode Exit fullscreen mode

we have looked into seven functions exposed from the go fmt package, now you can fully utilize the fmt package in your Go applications.

now it's time to harness the full power of go

molang.gif

what next: check out the official documentation to learn more about these functions.

💖 💪 🙅 🚩
robogeek95
Azeez Lukman

Posted on August 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related