Skip to main content
eLearner.app
Module 1 · Lesson 5 of 55/50 in the course~10 min
Module lessons (5/5)

Input/output with fmt

The standard library's fmt package is your main tool for printing to the console, formatting strings and reading input. If you have used printf in C you'll feel right at home, but with some extra refinement thanks to the %v and %T verbs.

Print, Println, Printf: three functions, three behaviors

Go
fmt.Print("ciao ", "mondo")    // "ciao mondo"  (niente newline finale)
fmt.Println("ciao", "mondo")   // "ciao mondo\n" (newline + spazi tra argomenti)
fmt.Printf("eta=%d\n", 36)     // "eta=36\n"    (format string esplicita)

The verbs you'll use all the time

VerbWhat it printsExample
%v"default value" — works on any type{Ada 36}
%+vlike %v but with field names in structs{Name:Ada Age:36}
%#v"Go-syntax" representation of the valuemain.User{Name:"Ada", Age:36}
%Tthe type of the valuefloat64
%dinteger in base 1042
%ffloat3.140000
%.2ffloat with 2 decimals3.14
%sstringAda
%q"quoted" string (with quotes and escapes)"Ada\n"
%tbooltrue
%xhexadecimal (lowercase)2a
%bbinary101010
Go
u := struct{ Name string; Age int }{"Ada", 36}
fmt.Printf("%v\n", u)   // {Ada 36}
fmt.Printf("%+v\n", u)  // {Name:Ada Age:36}
fmt.Printf("%T\n", 3.14) // float64

Sprintf: building strings without printing them

Same interface as Printf, but the result is returned to you as a string:

Go
msg := fmt.Sprintf("L'utente %s ha %d anni", "Ada", 36)
fmt.Println(msg) // L'utente Ada ha 36 anni

You'll use it constantly to build messages, logs and errors.

Errorf: strings + error wrapping

fmt.Errorf creates an error with Printf-style formatting. With the special verb %w you can wrap an existing error to preserve its chain (we'll cover this in depth in the Interfaces module):

Go
if _, err := os.Open("missing"); err != nil {
    return fmt.Errorf("apertura config: %w", err)
}

Your turn

Exercise#go.m1.l5.e1
Attempts: 0Loading…

Print the string 'ciao mondo' using fmt.Println.

Loading editor…
Show hint

`fmt.Println` takes a string and adds the newline itself.

Solution available after 3 attempts

Exercise#go.m1.l5.e2
Attempts: 0Loading…

Use fmt.Printf to print 'eta=36' followed by a newline, using the %d verb for the integer.

Loading editor…
Show hint

`Printf` doesn't add a newline: you have to include `\\n` in the format string.

Solution available after 3 attempts

Quiz#go.m1.l5.e3
Ready

Which verb prints the dynamic TYPE of a value?

Go
fmt.Printf("?\n", 3.14)
Answer options

Recap

  • Print/Println/Printf differ in spaces and newlines.
  • %v is the wildcard that works on any type; %+v shows field names.
  • %T prints the type (useful for quick debugging).
  • Sprintf builds strings; Errorf builds errors with wrapping (%w).
  • Printf does NOT add a newline: write it yourself in the format string.