Open In App

fmt Package in GoLang

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Packages in GoLang and Import in GoLang 

Technically defining, a package is essentially a container of source code for some specific purpose. Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensures that no code is repeated and that the main code is as concise as possible in a well-structured manner. Go provides various in-built packages to users so they can ease into coding with pre-defined basic functionality packages. One of such packages in the “fmt” package. fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.

Irrespective of what system you’ve installed Go on, find your $GOPATH, and then visit “$GOPATH/src/fmt/” on your system. You will find the following package-files in this particular directory. Well, we can say that these files all fall under the fmt package.

fmt packages file in Gopath

The image shows all the files situated in the “$GOPATH/src/fmt/” directory on your PC

Let’s look at the functions it provides to its users along with a brief description of each function:

     FUNCTIONS    

DESCRIPTION

Print

Print simply prints whatever input it receives as it is on theoutput console screen, beginning from the current cursor positionwithout appending any space or newlines unless explicitly coded.Apart from printing, it returns two values: the no of bytes writtenand error message in case any write error is encountered.

Printf

Printf formats the input string as the user’s choice and then printsthe formatted string onto the output console beginning from thecurrent cursor position without appending any space or newlinesunless explicitly coded. Apart from printing, it returns two values:the number of bytes written and error message in case any erroris encountered.

Println

Println works the same as print function except that it appends newline at the end of the input string and so whatever the output is, in the end, the cursor will move to the next line. Also in case, any variables are added to the input string then this function will ensure that the variables are separated by a space in between. Apart from printing, it returns two values: the no of bytes written and error message in case any write error is encountered.

Sprint

Sprint functions the same way as Print does. The only differenceis that Sprint returns the input string instead of printingon the output console.

Sprintf

Sprintf functions the same way as Printf does. The only differenceis that Sprintf returns the formatted input string insteadof printing on the output console.

Sprintln

Sprintln functions the same way as Println does. the only difference is that Sprintln returns the input stringinstead of printing on the output console.

Fprint

Unlike other print functions, the Fprint does not read or print anything on the console. Fprint formats the input string as per the default formatting and writes the formatted input string into the input file. Whenever two variables are encountered, space is automatically added in between by fprint. Apart from writing into the file, fprint returns two values: no. of bytes written& error message (if any error occurs).

Fprintf

Just similar to fprint but one difference that draws a line between the two is that fprintf formats according to the specified format and does not format according to the default formatting.Fprintf then writes the formatted input string into the file using. Apart from writing into the file, fprintf returns two values: no. of bytes are written and an error message (if any error occurs).

Fprintln

Works exactly the same as fprint. One extra point in Fprintln is thata newline is appended. The formatted input string will then bewritten into the mentioned file with the help of a writer. Apartfrom writing into the file, fprintln returns two values: no. of byteswritten and an error message (if any error occurs).

Scan

Scan collects input from the standard console, and stores this inputin successive arguments. Values that are separated by space ornewlines are treated as multiple values. These are stored inmultiple arguments. Apart from the on-screen scanning work,Scan also returns two values: no. of bytes read from consoleand an error message (if any).

Scanf

Just like the scanf in C language, where a format specifier ismentioned and then the address of the variable where theinput value is to be stored, Scanf in Go scans text read fromstandard input, and stores it in the arguments as per the specifiedformat. Apart from the on-screen scanning work, Scan alsoreturns two values: no. of bytes read from console andan error message (if any).

Scanln

Scanln works similar to Scan, but scanln stops scanning at anewline. Meaning that the last input character should befollowed by a newline for Scanln to stop scanning. Itmay as well be an End of file, no content no scan!

Sscan

Sscan works similar to scan except the difference that sscancollects input as the argument string and not the inputfrom the console screen in default formatting. And just likethe others it returns the two values: no of bytes & error message (if any).

Sscanf

Sscanf works similar to scanf except the difference that sscanfcollects input as the argument string and not the input fromthe console screen in mentioned formatting.

Sscanln

Sscanln is similar to Sscan but sscanln stops scanning at anewline. Meaning that the last input character should befollowed by a newline for Sscanln to stop scanning. Itmay as well be an End of file, no content no scan!

Fscan

Unlike other scan functions which collect input from useror the program console, in default formatting, Fscanreads content or text from the input file and returns theno of items parsed. It reads character wise, progressdirection depends on the pointer location you provide.

Fscanf

Fscanf works similar to fscan. The only difference is that fscanf reads from reader in the specified format rather than following the default formatting. The match-case is sensitive to whole words, spaces and newlines and hence, the argument string and text string must match entirely. Fscanf, apart from reading the characters, also returns the no of items parsed.

Fscanln

Fscanln is similar to Fscan but  Fscanln stops scanning at a newline. Meaning that the last input character should be followed by a newline for Fscanln to stop scanning. Itmay as well be an End of file, no content no scan!

Errorf

Errorf formats according to the mentioned format specifier and assigns this formatted string to a variable. This is the error message. This function allows you to printcustomized error messages, as per the user’s will, and print it to console as an error message.

Apart from the functions, Go has some in-built interfaces in its packages. The “fmt” package consists of the following interfaces. The following description has been referred from the official site of Go, you may click here to find out more.

        TYPES        

DESCRIPTION

Formatter

Formatter is an interface that makes custom formattingpossible. Calling format would be something likePrintf(f), Fprintf(f), Sprintf(f) etc.. to generate a customformatted output on the console.

GoStringer

Any code-value that has a GoString method directlyimplements the GoStringer interface implicitly.

ScanState

The ScanState interface holds declaration of valuablefunctions like:ReadRune, UnreadRune, SkipSpace, Token, Width & Read.Basically they tell more about the state of the custom scanner.

Scanner

All the scanning functions that we use – Scan, Scanfand Scanln etc… whenever used make a call to thescanner interface. The scanner interface makes it possiblefor us to collect input through console and/orinput argument strings.

State

It represents the state of the printer that’s passedto specific formats. It also holds informationabout flags and available options for the argumentstring’s format specifier.

Stringer

Any value that holds a string method (that makes the conversion of string argument into output possible)and uses the default formatting, directly implements the Stringer interface. For instance: Print, Sprint, etc.

So basically, in Go to implement any interface, we have just learned that we don’t have to do anything explicitly. Instead calling specific methods automatically implement the interfaces for the user. And it is through the implementation of the methods in interfaces that enable a particular value to take multiple forms. This is simply termed as polymorphism. Summing all this up, Interfaces in go are implemented implicitly when its methods are called and interfaces contribute to the concept of polymorphism.

Sample Codes for fmt Package:

1. Printing functions

Go




// Go code to visualise the differences
// between various print functions in fmt
  
package main
  
import "fmt"
  
func main() {
  
    // NOTE:
    // 1. Print(arg) prints arg as
    // it is on the console screen
    fmt.Print("Hello, welcome!")
    // OUTPUT: "Hello, welcome!"
      
    // Some variables to use in our code
    const x, id = "Ashika", 22
      
    // 2. Printf(arg) first formats arg
    // and then prints on the console screen
    fmt.Printf("\n1. Name %q and ID %d found!\n", x, id)
    // OUTPUT:
    // 1. Name "Ashika" and ID 22 found!
      
    // 3. Println(arg) does not format arg
    // It simply prints arg, appends any values
    // mentioned after arg and appends spaces in
    // between and also appends a new line at the end
    fmt.Println("2. Name %q and ID %d found!", x, id)
    // OUTPUT: 2. Name %q and ID %d found! Ashika 22
      
    // Print(arg) does not format, does not add
    // any spaces and does not append any newlines
    fmt.Print("3. Name %q and ID %d found!", x, id)
    // OUTPUT: 3. Name %q and ID %d found!Ashika22
      
    // 4. Sprint(arg) works similar to Print(arg)
    // The key difference is: Sprint returns arg as
    // it is as mentioned in the paranthesis and
    // Print(arg) prints on console screen.
    res := fmt.Sprint("\n4. Name %q and ID %d found!", x, id)
    fmt.Println(res)
    // OUTPUT:
    // 4. Name %q and ID %d found!Ashika22
      
    // 5. Sprintf(arg) works similar to Printf(arg)
    // The key difference is: Sprintf returns arg as
    // a formatted string as mentioned in the paranthesis
    // and Printf prints formatted arg on console screen
    res = fmt.Sprintf("5. Name %q and ID %d found!", x, id)
    fmt.Println(res)
    // OUTPUT: 5. Name "Ashika" and ID 22 found!
      
    // 6. Sprintln(arg) works similar to Println(arg)
    // The key difference is: Sprintln returns arg as
    // it is as mentioned in paranthesis and adds spaces
    // between variables and appends a newline to arg &
    // returns arg value while Println directly prints arg
    // onto the console screen.
    res = fmt.Sprintln("6. Name %q and ID %d found!", x, id)
    fmt.Print(res)
    // OUTPUT: 6. Name %q and ID %d found! Ashika 22
      
    fmt.Print("Goodbye!")
    // OUTPUT: "Goodbye!"
}


Output:

Hello, welcome!
1. Name "Ashika" and ID 22 found!
2. Name %q and ID %d found! Ashika 22
3. Name %q and ID %d found!Ashika22
4. Name %q and ID %d found!Ashika22
5. Name "Ashika" and ID 22 found!
6. Name %q and ID %d found! Ashika 22
Goodbye!

2. Scanning functions

Go




// Go code to demonstrate use & differences
// between various scan functions in fmt package
  
package main
  
import "fmt"
  
// Main function
func main() {
  
    fmt.Print("Hello, welcome!\n")
    var y, z, age int
    var name string
      
    // Scan function will collect input
    // until a space is encountered
    // from console and stores it in y
    fmt.Scan(&y)
    fmt.Printf("Scan: Y = %d\n", y)
      
    // Scanf collects user input in
    // the specified format and stores it
    // in name and age respectively
    fmt.Scanf("%s", &name)
    fmt.Scanf("%d", &age)
    fmt.Printf("Scanf: Name = %s , Age = %d\n", name, age)
      
    // Scanln will not do nothing if
    // a newline is encountered else
    // it stores input value in z
    fmt.Scanln(&z)
    // In our case after entering age we press
    // enter so this Scanln gets skipped and
    // thus 0 is stored in z as 0 is the
    // default value of int variable in Go
    fmt.Printf("Scanln: Z = %d\n", z)
  
    var a string
    var g int
      
    // GFG is stored in a
    // 10 is stored in g
    // In case of any error, error message
    // is stored in err1
    // Number of values encountered is stored in res1
    res1, err1 := fmt.Sscan("GFG 10", &a, &g)
    // In case of any error, this block will execute
    if err1 != nil {
        panic(err1)
    }
    fmt.Printf("Sscan -> n = %d , string = %s %d \n", res1, a, g)
      
    // GFG is stored in a
    // 5 is stored in g
    // In case of any error, error message
    // is stored in err2
    // Number of values encountered is stored in res2
    res2, err2 := fmt.Sscanf("String is GFG with 5 iterations"
                    "String is %s with %d iterations", &a, &g)
    // In case of any error, this block will execute
    if err2 != nil {
        panic(err2)
    }
    fmt.Printf("Sscanf -> n = %d , string = %s %d \n", res2, a, g)
      
    // GFG is stored in a
    // 17 is stored in g
    // In case a newline is encountered,
    // then Sscanln will raise a newline
    // panic error message
    // In case of any error, error message
    // is stored in err3
    // Number of values encountered is stored in res3
    res3, err3 := fmt.Sscanln("GFG 17", &a, &g)
    // In case of any error, this block will execute
    if err3 != nil {
        panic(err3)
    }
    fmt.Printf("Sscanln -> n = %d , string = %s %d \n", res3, a, g)
  
    fmt.Println("Goodbye!")
}


Input:

10
Ashika
20

Output:

Hello, welcome!
Scan: Y = 10
Scanf: Name = Ashika , Age = 20
Scanln: Z = 0
Sscan -> n =2 , string = GFG 10
Sscanf -> n = 2 , string = GFG 5
Sscanln -> n = 2 , string = GFG 17
Goodbye!

3. Errorf function demo

Go




// Go code to demonstrate
// the use of errorf function
// in fmt package
package main
  
import "fmt"
  
// Main function
func main() {
    const lazy = "I'm very lazy today"
      
    // Errorf formats according to the format specifier and
    // returns the string as a value that satisfies the error
    // and this error string are stored in err
    err := fmt.Errorf("Throwing error because: %q", lazy)
  
    // err.Error() will return the error message
    // and Println will print it on the output console
    fmt.Println(err.Error())
}


Output:

Throwing error because: "I'm very lazy today"

Visual Outputs of Sample Codes On Visual Studio Code:

Output of printing functions sample code

 

Note: The scanln value is showing 0 as an output. It is so because scanln could even collect the user input, the newline from previous input has forced scanln to stop collecting input from the user. And default value in Go for int is a 0 thus the value 0 for Z.

Output of scanning functions sample code

Output of errorf function sample code



Last Updated : 25 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads