fmt Package in GoLang - GeeksforGeeks

25 Aug, 2020
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.
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
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
Scan
Scanf
Scanln
Sscan
Sscanf
Sscanln
Fscan
Fscanf
Fscanln
Errorf
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
GoStringer
ScanState
Scanner
State
Stringer
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.
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 functionfunc 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 packagepackage main  import "fmt"  // Main functionfunc 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"

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
Golang-Packages
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Inheritance in GoLang
How to Trim a String in Golang?