Introduction to the `fmt` Package

The fmt package in Go is essential for formatted I/O operations such as printing and scanning. This package provides the most common operations you're going to use for console output and simple formatted input.

Printing with `fmt`

The `fmt` package offers various functions for printing:

  • fmt.Print()
  • fmt.Println()
  • fmt.Printf()

Using Print and Println

The simplest functions in the fmt package are Print() and Println(), which print text to the standard output.

package main

import "fmt"

func main() {
    fmt.Print("Hello, World!")
    fmt.Println("Hello, World!") // This adds a new line at the end
}

Formatted Printing with Printf

The Printf function allows for formatted strings using verbs, similar to C's printf:


func main() {
    age := 30
    name := "John Doe"
    fmt.Printf("%s is %d years old.\n", name, age)
}

Formatting Verbs

Some of the most common verbs used with Printf include:

  • %s - for strings.
  • %d - for integers.
  • %f - for floating-point numbers.
  • %.2f - for formatting floats to 2 decimal points.

func main() {
    price := 19.99
    discount := 0.15
    fmt.Printf("Price: $%.2f\nDiscount: %.0f%%\n", price, discount*100)
}

Reading Input with `fmt`

The fmt package can also read input from users. The primary function for this is Scanln:


func main() {
    var name string
    var age int
    fmt.Print("Enter your name and age: ")
    fmt.Scanln(&name, &age)
    fmt.Printf("Hello %s, you are %d years old.\n", name, age)
}

Conclusion

The fmt package is a convenient tool in Go for handling basic formatted input and output. It's straightforward for those familiar with formatted I/O from other languages, enabling easy adaptation and productivity.