Introduction
Today, we will cover the basics of print functions in the fmt package using the GO programming language.
These functions include:
fmt.Print
fmt.Prinln
fmt.Printf
So let's not waste our time and dive in.
What is the "fmt" package
In GO, fmt
stands for format. fmt is one of the most Basic & Crucial in GO as it handles the basic input and output and also allows formatting.
These days, most programming languages like Python and Miniscript have such basic functions built into them.
But to date, some programming languages like GO, C++, and C require users to import these packages separately into their code. C and C++ have the stdio
library for such functions.
How do I import the "fmt" Package
It's very simple to import any package into your GO code. All you have to do is write the following command and the top of your code after the package declaration.
package main //package declaration.
import "fmt" //importing fmt
Simmiliarly, you could import "math", "time", or any other package into your GO program.
What about the Error
You might have already observed that after you import the package, an error occurs.
"fmt" imported and not used
This is called an UnusedImport Error.
UnusedImport occurs when an import is unused.
As we haven't used the package fmt
in our program, GO will show an error until you use it.
This error also occurs when a variable is declared and initialised but not used in the program.
Understanding the functions
Now comes the part of understanding the functions the fmt package provides us with:
fmt.Print()
This function prints the argument without creating a new line.
Example:
package main
import (
"fmt"
)
func main() {
fmt.Print("Hello")
fmt.Print(" World")
}
This would output
Hello World
fmt.Println()
But if in the same scenario, if we had used fmt.Println()
instead of fmt.Print()
then the output would be:
Hello
World
fmt.Printf()
Many times, we need to add variables between strings.TO do this with Println
or Print
, we have to use this approach:
func main() {
firstName := "Steve"
lastName := "Jobs"
fmt.Println("Hello " + firstName + " " + lastName)
}
But Printf
makes our work easy by using Format Specifier.
Now, what a Format Specifier is is a different topic. Currently, we can suppose them as placeholders for the variable.
Now, to write the same code with Printf
, we would use this approach.
func main() {
firstName := "Steve"
lastName := "Jobs"
fmt.Printf("Hello %s %s", firstName, lastName)
}
Outro
That's it for today. Make sure to drop down your thoughts in the comment section.
Other Post:
👉What is GO
👉Writing First Program in GO!
👉Variables and GO!
YouTube Channel: Dat One Dev
Drop your thoughts down in the comments
Till then, stay Awesome and stay cool.
Why are you tagging an article about Go with C++ and Rust?