Published on

Print Formatting in go (golang)

Authors

If you come from other programming languages like JavaScript, the concept of having to add percentage signs when printing values might seem foreign to you. But in other programming languages, you often have to add a percentage sign followed by a letter. That is also how Print Formatting works in go (golang).

The symbol we use in every format specifier is %. Followed by letter with specific letter

Format Ppecifiers in C

The concept of Format specifiers comes from the C programming language. Format specifiers in C are used to take inputs and print the output of its type. The symbol we use in every format specifier is %. Format specifiers tell the compiler about the type of data given or input and the type of data that must be printed in the console.

Format Ppecifiers in go (golang)

Go uses almost the same format specifiers as C but slightly simplifies them.

Here are a few examples

General

SPECIFIERPURPOSE
%vthe value in a default format
%#va Go-syntax representation of the value
%Ta Go-syntax representation of the type of the value
%%a literal percent sign; consumes no value

Integer

SPECIFIERPURPOSE
%bbase 2
%cthe character represented by the corresponding Unicode code point
%dbase 10
%obase 8
%Obase 8 with 0o prefix
%qa single-quoted character literal safely escaped with Go syntax.
%xbase 16, with lower-case letters for a-f
%Xbase 16, with upper-case letters for A-F
%UUnicode format: U+1234; same as "U+%04X"

String

SPECIFIERPURPOSE
%sthe uninterpreted bytes of the string or slice
%qa double-quoted string safely escaped with Go syntax
%xbase 16, lower-case, two characters per byte
%Xbase 16, upper-case, two characters per byte

Default formator for %v

TYPEDEFAULT
bool%t
int, int8 etc.%d
uint, uint8 etc.%d, %#x if printed with %#v
float32, complex64, etc%g
string%s
chan%p
pointer%p

Example: %T will print the type of a variable

import (
	"fmt"
)

func main() {
	num := 1

	fmt.Printf("The variable num is of type %T \n", num)
}
The variable num is of type int