fmt package contains lots of functions. So to save time, we will discuss the most frequently used functions. Let’s start with fmt.Print inside our main function.
Print Functions
Print does not format anything, it simply takes a string and prints it.
Println
Next, we havePrintln which is the same as Print but it adds a new line at the end and also inserts space between the arguments.
Printf
Next, we havePrintf also known as “Print Formatter”, which allows us to format numbers, strings, booleans, and much more.
Let’s look at an example.
%s was substituted with our name variable.
But the question is what is %s and what does it mean?
So, these are called annotation verbs and they tell the function how to format the arguments. We can control things like width, types, and precision with these and there are lots of them. Here’s a cheatsheet.
Annotation Verbs
Now, let’s quickly look at some more examples. Here we will try to calculate a percentage and print it to the console.77.78 which is 2 points precision, we can do that as well by using .2f.
Also, to add an actual percent sign, we will need to escape it.
Sprint Functions
This brings us toSprint, Sprintln, and Sprintf. These are basically the same as the print functions, the only difference being they return the string instead of printing it.
Let’s take a look at an example.
Sprintf formats our integer as hex or binary and returns it as a string.
Multiline Strings
Lastly, we have multiline string literals, which can be used like this.Great! But this is just the tip of the iceberg…so make sure to check out the go doc for
fmt package.