DEV Community

Cover image for Exploring the Go fmt package
Azeez Lukman
Azeez Lukman

Posted on

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.

Top comments (8)

Collapse
 
jessecrypted profile image
jesse-crypted

Thanks, learned alot

Collapse
 
stiby profile image
stiby

Nice article, worth noting to readers these functions are fairly standard in most languages, great when approaching/learning new languages. There is a debate if Printf first appeared in Algor68 or C but sometime in the mid/early 1970's it appears in the documentation.

Collapse
 
kishanbsh profile image
Kishan B

Never knew fmt.Scan existed. Thanks for sharing! :-)

Collapse
 
robogeek95 profile image
Azeez Lukman

Thanks for reading, I'm glad you learnt something new

Collapse
 
bitfield profile image
John Arundel

Excellent piece! I did a deep-dive video a while ago exploring the source code to the 'fmt' package:

youtube.com/watch?v=Kj0poyw57iI
youtube.com/watch?v=QZIPaXfunyM

Collapse
 
robogeek95 profile image
Azeez Lukman

Hi John, this is a great resource. Thanks for sharing.
I just Subscibed :)

Collapse
 
verh010m profile image
verh010m

For those who have started to learn the language, such articles are the best solution. thank you

Collapse
 
robogeek95 profile image
Azeez Lukman

Nice! Thanks for the kind words. Please subscribe to get more great articles like this at your fingertips