In this tutorial, we will learn about the fmt package.
By the end of this tutorial, you’ll have a solid understanding of the fmt package covering everything from printing, formatting data, and reading input.
Printing data
We have already seen how to use the Println method. One alternative method is called Print.
fmt.Print("Hello!")
fmt.Print("Go is awesome")
This will not insert any new line and both print statements will end up on the same line. If we would like to add a newline we have 2 options.
We can use the escape key \n and it will add a new line.
fmt.Print("Hello!\n")
fmt.Print("Go is awesome")
We could also replace it by using Println and the result will be the same
fmt.Println("Hello!")
fmt.Println("Go is awesome")
It’s possible to pass multiple values to the print statement and it will output all of them.fmt
fmt.Print("My name is", "Patrik")
We can also output variables to the console
name := "Patrik"
lang := "Go"
fmt.Println("My name is", name)
fmt.Println("I love the" + lang + " programming language")
Formatting data
Printf & Sprintf
In Go we can also use something called formatting. It simplifies inserting variables into text, making the code more readable and easier to manage.
To format data We can use the Printf method.
name := "Patrik"
countBurgers := 2
fmt.Printf("My name is %s and I had %d burgers today!", name, age)
%s and %d are placeholders inserted into strings and indicate the type of data and its display format.
There is also an alternative method called Sprintf instead of priting the formatted string it will return it.
name := "Patrik"
countBurgers := 2
sentence := fmt.Sprintf("My name is %s and I had %d burgers today!", name, age)
fmt.Println(sentence)
Format Specifiers
Here are the different Format Specifiers grouped by type that can be used when formatting data.
General
%vDefault format for the variable%#vA Go-syntax representation of the value%TPrints the type of the value
Boolean
%tBoolean (trueorfalse)
Integer
%dDecimal integer%bBinary integer%oOctal integer%xHexadecimal integer (lowercase letters)%XHexadecimal integer (uppercase letters)%cThe character represented by the corresponding Unicode code point%qA single-quoted character literal safely escaped with Go syntax.
Floating-Point and Complex Numbers
%fDecimal floating point, no exponent%bScientific notation (with binary exponent), e.g.,-123456p-78%eScientific notation, e.g.,-1.234456e+78%EScientific notation, e.g.,-1.234456E+78%gCompact representation (chooses%eor%fautomatically)%GCompact representation (chooses%Eor%Fautomatically)
String and Slices
%sString or slice of bytes%qA double-quoted string safely escaped with Go syntax%xBase 16, lowercase letters, two characters per byte of the argument%XBase 16, uppercase letters, two characters per byte of the argument
Pointer
%pPointer address
Width and Precision
%.2fFloating point with 2 digits after the decimal point%9fFloating point with 9 characters width%9.2fWidth of 9 and precision of 2%9sString with a minimum width of 9 characters, right-justified by default%-9sString with a minimum width of 9 characters, left-justified
Padding and Alignment
%05dInteger padded with zeros to a width of 5 digits% 5dInteger right-aligned in a field of 5 characters wide%-5sString left-aligned in a field of 5 characters wide
Reading user input
So far we have only been printing data but what if we want to read user input. To do this we can use the Scan method.
var name string
var age int
fmt.Println("Enter your name: ")
fmt.Scan(&name)
fmt.Println("Enter your age: ")
fmt.Scan(&age)
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
First, we declare two variables. After that, we ask the user to enter their name. Next, we use the Scan method to receive the user input. Notice we put & before the variable, the reason for this is we want to pass the memory address of the variable so the scan method can update that address with the received value. After that, we do the same for the age. As a last step, we print out the values using the Printf method.
You can also scan multiple values with 1 Scanstatement.
var favColor1 string
var favColor2 string
fmt.Println("Enter your two favorite colors: ")
fmt.Scan(&favColor1, &favColor2)
fmt.Println("favorite colors ", favColor1, favColor2)
This reads input values until it encounters spaces or newlines, and it assigns them to favColor1 and favColor2. The function continues to prompt until all specified variables are filled, allowing inputs across multiple lines.
If you want both values to be read from the same line you can use Scanln
var favColor1 string
var favColor2 string
fmt.Println("Enter your two favorite colors: ")
fmt.Scanln(&favColor1, &favColor2)
fmt.Println("favorite colors ", favColor1, favColor2)
It reads all required input from a single line, separated by spaces, and assigns them to the variables in one go.
If we can the input to match a specific format we can use the method Scanf.
var favColor1 string
var favColor2 string
fmt.Println("Enter your two favorite colors separated by a comma (e.g., red,blue): ")
fmt.Scanf("%s,%s", &favColor1, &favColor2)
fmt.Printf("Your favorite colors are: %s and %s.\n", favColor1, favColor2)
We use the fmt.Scanf with %s,%s to tell Go to expect two string inputs separated by a comma. fmt.Printf formats and displays a message with the user’s favorite colors.
Conclusion
Full source code can be found here Github
In this tutorial, we’ve explored how to print, format, and read data in Go using the fmt package. We covered basic printing with fmt.Print and fmt.Println, detailed formatting with fmt.Printf and fmt.Sprintf, and how to capture user input withfmt.Scan, fmt.Scanln, and fmt.Scanf. In the next tutorial, we gonna talk about arrays & slices.