Go Output

Go's fmt package provides simple, flexible tools for printing and formatting output, including Println, Printf, and Sprintf.

Printing with fmt.Println

fmt.Println prints one or more values to the console, separates them with spaces, and adds a newline at the end automatically.

Using fmt.Println

package main

import "fmt"

func main() {
    fmt.Println("Go", "makes", "printing", "easy")
}

Formatted Output with fmt.Printf

fmt.Printf lets you build a formatted string using verbs, special placeholders starting with %, and does not add a newline automatically. Common verbs include %s for strings, %d for integers, %f for floats, and %v for any value's default representation.

VerbMeaning
%sString value
%dBase-10 integer
%fFloating-point number
%vDefault format for any value
%TThe type of a value

Using fmt.Printf

package main

import "fmt"

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

Building Strings with fmt.Sprintf

fmt.Sprintf works exactly like Printf, but instead of printing to the console it returns the formatted text as a string, which you can store in a variable and use later.

Using fmt.Sprintf

package main

import "fmt"

func main() {
    name := "Maria"
    age := 29
    summary := fmt.Sprintf("%s is %d years old", name, age)
    fmt.Println(summary)
}
  • fmt.Print — writes values with no automatic spacing or newline
  • fmt.Println — writes values separated by spaces, then a newline
  • fmt.Printf — writes a formatted string using verbs, no automatic newline
  • fmt.Sprintf — returns a formatted string instead of printing it
  • fmt.Sprintln — returns values joined with spaces and a trailing newline
Note: Reach for Printf or Sprintf whenever you need precise control over number formatting, such as limiting decimal places with a verb like %.2f.
Note: Unlike Println, Printf does not add a newline for you — remember to include \n at the end of your format string when you want one.

Exercise: Go Output

Which package must be imported to print output to the console?