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
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
| Verb | What it prints | Example |
|---|---|---|
%v | "default value" — works on any type | {Ada 36} |
%+v | like %v but with field names in structs | {Name:Ada Age:36} |
%#v | "Go-syntax" representation of the value | main.User{Name:"Ada", Age:36} |
%T | the type of the value | float64 |
%d | integer in base 10 | 42 |
%f | float | 3.140000 |
%.2f | float with 2 decimals | 3.14 |
%s | string | Ada |
%q | "quoted" string (with quotes and escapes) | "Ada\n" |
%t | bool | true |
%x | hexadecimal (lowercase) | 2a |
%b | binary | 101010 |
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) // float64Sprintf: building strings without printing them
Same interface as Printf, but the result is returned to you as a
string:
msg := fmt.Sprintf("L'utente %s ha %d anni", "Ada", 36)
fmt.Println(msg) // L'utente Ada ha 36 anniYou'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):
if _, err := os.Open("missing"); err != nil {
return fmt.Errorf("apertura config: %w", err)
}Your turn
Print the string 'ciao mondo' using fmt.Println.
Show hint
`fmt.Println` takes a string and adds the newline itself.
Solution available after 3 attempts
Use fmt.Printf to print 'eta=36' followed by a newline, using the %d verb for the integer.
Show hint
`Printf` doesn't add a newline: you have to include `\\n` in the format string.
Solution available after 3 attempts
Which verb prints the dynamic TYPE of a value?
fmt.Printf("?\n", 3.14)Recap
Print/Println/Printfdiffer in spaces and newlines.%vis the wildcard that works on any type;%+vshows field names.%Tprints the type (useful for quick debugging).Sprintfbuilds strings;Errorfbuilds errors with wrapping (%w).Printfdoes NOT add a newline: write it yourself in the format string.