AppDividend
Latest Code Tutorials

Formatted I/O Functions In Golang | fmt Package Example

0

Package fmt implements the formatted I/O with functions analogous to C’s printf and scanf. If we want to print the string in the console, then we need to use fmt package in Golang. The format ‘verbs’ are derived from C language but are more straightforward. Before we start our Formatted I/O Functions example, Let’s start with templates in Go.

What are templates?

The main concept in the fmt package is that it formats the template.

This is a string that contains a text you want to print plus some placeholders (also called verbs) that tell fmt package where to insert your variables.

String interpolation in Go

The string literal can have placeholders.

These placeholders are also called as verbs.

These placeholders can be replaced by the actual variables using string formatting functions provided by the fmt package.

Some of these verbs or placeholders in Golang might appear in %x format where the formatting verb must start with the %(percentage), and x is the formatting operator.

Let’s talk more about Verbs.

Verbs in Golang

  1. %v is a generic placeholder. It will automatically convert the variable into the string with some default options. This is generally useful when printing the primitives such as the strings or numbers, and you don’t need any other specific options.
  2. %#v prints your variable in Golang syntax. This means you could copy the output and paste it into your code, and it will syntactically correct. It is useful when working with the data structure like structs and slices because it will print out the types and field names.
  3. %T prints your variable’s type. This placeholder is useful for debugging if your data is passed as an interface{}, and you want to see what it’s concrete type.
  4. %d prints the integer in base-10. You can do the same with the %v, but this way is more explicit.
  5. %x and %X print the integer in base-16. One helpful trick, though, is that you can pass in a byte slice, and it’ll print each byte as a two-digit hex number.
  6. %f prints the floating-point number without an exponent. You can do the same with the %v, but this becomes more useful when we add the width and precision flags.
  7. %q prints the quoted string. It is useful when your data may have invisible characters (such as zero width space) because the quoted-string will print them as escape sequences.
  8. %p prints the pointer address of your variable. This one is beneficial when you are debugging code, and you want to check if the different pointer variables reference the same data.

Printing in Golang

Printing something to the standard output in Golang is very easy.

The most common use of formatting is to print to the terminal window through STDOUT. It can be done with the Print functions:

You need to import fmt package (which stands for format but Go developers like to call it fumpt) and call the functions like Print to write something to the standard output like terminal or command prompt and to get the input from user, you can use the Scanf() function in Go.

Formatted I/O Functions

See the following code example.

// hello.go

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Today is Mandalorian's fifth episode")
}

Output

➜ go run hello.go
Today is Mandalorian's fifth episode

In the above code, we have used the Println() function.

Println() function formats using a default formats for its operands and writes the standard output.

Spaces are always added between the operands, and the new line is appended.

It returns a number of bytes written, and any write error encountered.

The Printing section of the fmt package is huge.

We have the couple of different functions like Print, and Printf which can achieve this.

Let’s focus on Print and Printf first.

Okay, now let’s see Print and Printf function one by one.

fmt.Print(args…) (n int, e error)

Print formats using a default formats for its operands and writes to standard output.

Spaces are added between operands when neither is the string.

It returns a number of bytes written, and any write error encountered.

See the following code example.

// hello.go

package main

import (
	"fmt"
)

func main() {
	fmt.Print("Today is Mandalorian's fifth episode")
}

Output

➜ go run hello.go
Today is Mandalorian's fifth episode

The Print function returns a number of bytes written, and any error occurred while writing, but we generally ignore these return values.

fmt.Println(args…) (n int, e error)

Println() function formats the default formats for its operands and writes to standard output.

Spaces are always added between operands, and the new line is appended. It returns a number of bytes written, and any write error encountered.

See the following code.

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Today is Mandalorian's fifth episode")
}

Output

➜  hello go run hello.go
Today is Mandalorian's fifth episode
➜  hello

Golang Println() is also the variadic function, which means it can also accept the multiple arguments.

It always concatenates these arguments with a space in between and writes to the standard output with the trailing newline.

fmt.Printf(args…) (n int, e error)

Printf() function formats according to the format specifier and writes to standard output.

It returns the number of bytes written, and any write error encountered.

Golang Printf() function is also a variadic function, which means it can also accept multiple arguments.

See the following code.

// hello.go

package main

import (
	"fmt"
)

func main() {
	fmt.Printf("Today is Mandalorian's fifth episode")
}

Output

➜ go run hello.go
Today is Mandalorian's fifth episode

Go fmt.Printf() excepts first arguments to be the string literal with some placeholders.

Later arguments will be sequentially substituted in the placeholder. 

The number of arguments except an initial string should be equal to the number placeholders we used.

Printf does not end with the trailing newline (and there is no Prinfln function) and has the same return values of the Print function.

fmt.Scan(n int, e error)

Scan() function scans the text read from standard input, storing successive space-separated values into successive arguments.

Newlines count as the space. It returns a number of elements successfully scanned inputs.

If that is less than the number of arguments, err will report why it has happended.

See the following code.

// hello.go

package main

import (
	"fmt"
	"os"
)

func main() {
	var name string
	var rollno int
	if _, err := fmt.Scan(&name, &rollno); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("Your name is: %s\n", name)
	fmt.Printf("Your roll no is: %d\n", rollno)
}

Output

➜ go run hello.go
krunal
10
Your name is: krunal
Your roll no is: 10

fmt.Scanf(n int, e error)

Scanf scans text read from the standard input, storing successive space-separated values into successive arguments as determined by the format.

It returns the number of elements successfully scanned.

Newlines in the input must match newlines in the format.

There is one exception: the verb %c always scans the next rune in the input, even if it is the space (or tab, etc.) or newline. Keep in mind this scenario.

See the following code.

// hello.go

package main

import (
	"fmt"
)

func main() {
	var name string
	var rollno int

	fmt.Printf("Enter your name: ")
	fmt.Scanf("%s", &name)

	fmt.Printf("Enter your rollno: ")
	fmt.Scanf("%d", &rollno)

	fmt.Printf("Your name is: %s\n", name)
	fmt.Printf("Your roll no is: %d\n", rollno)
}

Output

go run hello.go
Enter your name: krunal
Enter your rollno: 10
Your name is: krunal
Your roll no is: 10

So, Golang Scanf() function has successfully scanned the name and rollno input values, stores it in the variables, and returns those values.

fmt.Scanln(n int, e error)

Scanln is similar to Scan but stops scanning at a newline, and after the final item, there must be a newline or EOF.

Conclusion

There are so many Formatted I/O functions in Golang. You can refer to the Go documentation: Go fmt package.

In this article, we have seen how to print string in console, printing verbs, how to get the input from users like C language.

Formatted I/O Functions In Golang | fmt Package Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.