Skip to content

Go fmt Package

The fmt package (short for "format") is the most commonly used package for printing and reading data.

1. Printing Functions

There are three main ways to print output:

  • fmt.Println: Prints arguments with spaces between them and a newline at the end.
  • fmt.Print: Like Println, but no newline or extra spaces.
  • fmt.Printf: Used for formatted strings (incorporates "verbs" like %d).
package main

import "fmt"

func main() {
    name := "Go"
    version := 1.21

    fmt.Println("Hello", name) // Prints "Hello Go" + \n
    fmt.Printf("%s version is %f\n", name, version)
}

2. Creating Strings (Sprintf)

If you want to "print" to a variable instead of the console, use fmt.Sprintf.

s := fmt.Sprintf("Formatting %s into a string", "this")
fmt.Println(s)

3. Reading Input (Scan)

To get input from the user, use fmt.Scan or fmt.Scanln.

package main

import "fmt"

func main() {
    var age int
    fmt.Print("Enter your age: ")
    fmt.Scan(&age) // Takes a pointer to the variable
    fmt.Println("Your age is:", age)
}

4. Errors (Errorf)

fmt.Errorf is a quick way to create a formatted error message.

err := fmt.Errorf("user %d not found", 404)
fmt.Println(err.Error())

Quick Summary

Function Description
Print / Println Basic console output.
Printf Formatted console output.
Sprintf Returns a formatted string.
Scan Reads input from console.
Errorf Creates a formatted error.