Fmt provides printing to standard output (usually the console) and formatting of strings capabilities.

The basics of Print and Println

The main difference between fmt.Print and fmt.Println is that you only get a newline/carriage return by default with the second one. Other than that, you can make use of either for string formatting.

Firstly, we need to import the fmt module as follows:

1
2
3
4
5
6
7
package main

import "fmt" // <--- include fmt

func main() {
    // main
}

Example of fmt.Print

1
2
3
fmt.Print("This is a Print test")

// "This is a Print test"

This will print to standard output without a newline at the end.

Example of fmt.Println

1
2
3
4
fmt.Println("This is a Println test")

// "This is a Println test\n   <--- newline added
//  "
This will print to standard output with a newline at the end.

Printing variables

1
2
3
4
5
const number = 37

fmt.Println("The number is", number)

// "The number is 37"

Notice how a space is automatically added between the strings above.

Printing complex structures

1
2
3
4
5
6
7
8
items := []int {10, 20, 30, 40, 50}

length, err := fmt.Println(items)

fmt.Println(<meta charset="utf-8">length, err)

// [10 20 30 40 50]
// 14 nil

The above prints out the list of item, followed by the length of that string, and nil as the error.

Introducing Printf and Sprintf

These are quite similar to the Print methods we looked at previously, but they offer more flexibility for formatting.

These functions make use of the formatting verbs, such as %v, %#v, %T and %t to name yet a few. You can get a full list from https://pkg.go.dev/fmt.

How to print decimal values

1
2
fmt.Printf("%d\n", 20)
// 20

How to print hexadecimal values

1
2
fmt.Printf("%x\n", 123.45)
// 14

How to print a boolean value

1
2
fmt.Printf("%t\n", 2 > 1)
// true

How to print floating point numbers

1
2
fmt.Printf("%f\n", 123.45)
// 123.450000

How to print exponent numbers (scientific notation)

1
2
fmt.Printf("%e\n", 123.45)
// 1.234500+02

More advanced usages

1
2
3
4
5
6
7
8
9
fmt.Printf("%d, %d", 10, 20)
// 10 20

fmt.Printf("%[2]d %[1]d", 10, 20)
// 20 10

// decimal, octal and hexadecimal
fmt.Printf("%d %#[1]o %#[]x\n", 52)
52 064 0x34

Formatting by precision

Decimal precision

1
2
fmt.Printf("%.2f\n", 123.4567)
// 123.46
1
2
3
// print with 10 spaces
fmt.Printf("%10f\n", 123.4567)
// 123.456700
1
2
fmt.Printf("%10.2f\n", 123.4567)
// "    123.46"
1
2
fmt.Printf("%+10.2f\n", 123.4567)
// "   +123.46"

Pad with 0s instead of spaces

1
2
fmt.Printf("%010.2f\n", 123.4567)
// 0000123.46