SyntaxPilot
Courses/Go Programming/Lesson 18

Go Programming · Lesson 18 of 89 · 14 min

Formatted output and reading input

fmt.Print/Println/PrintfSprintfFprintfformat verbs (%v, %+v, %#v, %T, %d, %b, %x, %o, %s, %q, %f, %e, %t, %p)width and precisionfmt.Scan and Scanlnbufio.Scanner for line inputos.Stdinos.Args

These are the notes for Go episode 18. So far our programs only talk, and they talk messily: ragged columns, 37.5 next to 30, and 0.30000000000000004. Today Raju's chai stall gets a bill that looks neat, and a program that listens to what the customer orders. You will learn fmt.Print, Println and Printf, format strings and verbs (%v %+v %#v %T %d %b %o %x %s %q %f %e %t %p %%), width and precision (%-12s, %8.2f), Sprintf, Fprintf, the three standard streams (os.Stdin, os.Stdout, os.Stderr), a first look at io.Writer, fmt.Scan and fmt.Scanln, bufio.Scanner for whole lines until EOF, and os.Args for command-line arguments. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24). Where a program reads input, the text typed into the compiler's program input box is shown too.

The problem: a messy bill

Raju writes bills by hand: names on the left, rupees lined up on the right, always two digits after the point. Here is the same bill printed with what we knew so far:

package main

import "fmt"

func main() {
    fmt.Print("Bill for table ", 4, "\n")
    fmt.Print("Items:", 3, 2, "\n")

    chai, samosa := 12.5, 15.0
    fmt.Println("masala chai", 3, chai*3)
    fmt.Println("samosa", 2, samosa*2)
    fmt.Println("Total:", chai*3+samosa*2)

    a, b := 0.1, 0.2
    fmt.Println("Round-off:", a+b)
}
Bill for table 4
Items:3 2
masala chai 3 37.5
samosa 2 30
Total: 67.5
Round-off: 0.30000000000000004
  • fmt.Print writes its values one after another with no newline at the end. It adds a space between two values only when neither is a string: so "Items:", 3 gives Items:3, but 3, 2 gives 3 2.
  • fmt.Println ("print line") always puts a space between values and a newline at the end.
  • Neither one formats: the columns don't line up, 37.5 has one decimal and 30 has none.
  • 0.1 + 0.2 prints 0.30000000000000004: a float64 stores the closest binary approximation of a decimal number, and Println shows every digit needed to identify it. (With constants, fmt.Println(0.1 + 0.2) prints 0.3, because constant arithmetic is exact; episode 5. The variables a and b force real float64 maths.)

We need to control the shape of the output.

Printf, format strings and verbs

Think of a bill book from the stationery shop: most words are already printed, with blanks to fill in, and each blank has a size.

Bill book In Go Name
The printed form "%s x %d = %.2f\n" the format string: fixed text plus placeholders
One blank: "item ____" %s, %d, %f a verb: a placeholder starting with % that says what goes there and how to show it
The size of a box %8.2f width (8) and precision (2)
Filling in the form fmt.Printf(format, values...) Printf = print formatted
  • fmt.Printf(format, a, b, c) takes the format string first, then the values. Verbs are filled in order: the first verb takes the first value, and so on.
  • %s = a string, %d = a whole number in decimal (base 10), %f = a floating-point number (a number with a decimal point).
  • Printf does not add a newline. Write \n (backslash n, the newline escape) yourself.
package main

import "fmt"

func main() {
    item, qty, rate := "masala chai", 3, 12.5

    fmt.Printf("%s x %d = %f\n", item, qty, float64(qty)*rate)
    fmt.Printf("%s x %d = %.2f\n", item, qty, float64(qty)*rate)

    a, b := 0.1, 0.2
    fmt.Printf("Round-off: %.2f\n", a+b)
    fmt.Printf("no newline")
    fmt.Printf("...see?\n")
}
masala chai x 3 = 37.500000
masala chai x 3 = 37.50
Round-off: 0.30
no newline...see?
  • Plain %f always shows 6 decimal places.
  • %.2f: the number after the dot is the precision, here 2 decimal places. The value is rounded, so 0.30000000000000004 prints as 0.30. The stored value hasn't changed; only how it is shown.
  • Forgetting \n joins the next output onto the same line.
  • float64(qty) converts the int to float64 before multiplying (episode 4: Go never mixes types silently).

Width, padding and alignment

The number before the dot is the width: the minimum number of characters to use. If the value is shorter, extra spaces are added; those spaces are called padding.

package main

import "fmt"

func main() {
    items := []string{"masala chai", "samosa", "bun maska"}
    qty := []int{3, 2, 1}
    amt := []float64{37.5, 30, 35}

    fmt.Printf("%-12s %3s %8s\n", "Item", "Qty", "Amount")
    for i := range items {
        fmt.Printf("%-12s %3d %8.2f\n", items[i], qty[i], amt[i])
    }
    fmt.Printf("%-16s %8.2f\n", "Total", 102.5)

    fmt.Printf("[%5d] [%-5d] [%05d]\n", 42, 42, 42)
}
Item         Qty   Amount
masala chai    3    37.50
samosa         2    30.00
bun maska      1    35.00
Total              102.50
[   42] [42   ] [00042]
Verb Meaning Result for 42 / "tea" / 3.14159
%5d width 5, right-aligned (padding on the left) [ 42]
%-5d - flag: left-aligned (padding on the right) [42 ]
%05d 0 flag: pad with zeros [00042]
%-12s a string in 12 characters, left-aligned tea
%8.2f 8 characters wide, 2 decimals, right-aligned 3.14
  • Alignment is which side the text sits on inside its width. Numbers are usually right-aligned (so the decimal points line up) and names left-aligned.
  • Width is a minimum: a longer value is never cut. (%.3s does cut a string to 3 characters; see the table below.)
  • The Total row uses width 16 = 12 + 1 space + 3, so its amount lines up under the others.

Debugging verbs: %v, %+v, %#v and %T

While building a program you often want to peek inside a value. A struct groups named values called fields into one value (seen briefly in episode 15; episode 19 covers structs fully).

package main

import "fmt"

func main() {
    type order struct {
        item string
        qty  int
        paid bool
    }
    o := order{"samosa", 3, false}
    fmt.Printf("%v\n", o)
    fmt.Printf("%+v\n", o)
    fmt.Printf("%#v\n", o)
    fmt.Printf("%T\n", o)

    tables := []int{4, 7}
    fmt.Printf("%v %#v %T\n", tables, tables, tables)
}
{samosa 3 false}
{item:samosa qty:3 paid:false}
main.order{item:"samosa", qty:3, paid:false}
main.order
[4 7] []int{4, 7} []int
Verb Shows Example output
%v the value in its default format {samosa 3 false}
%+v for structs, adds field names {item:samosa qty:3 paid:false}
%#v the value as Go syntax (type, quotes) main.order{item:"samosa", ...}
%T the type of the value main.order, []int
  • %v works on any value: that's what Println uses for every argument.
  • main.order means the type order declared in package main.

More verbs: bases, scientific notation, bools, %% and %p

package main

import "fmt"

func main() {
    n := 255
    fmt.Printf("%d %b %o %x %X\n", n, n, n, n, n)
    perm := 0644
    fmt.Printf("%d %o\n", perm, perm)

    india := 1428600000.0
    fmt.Printf("%f\n%e\n%.2e\n", india, india, india)

    open := true
    fmt.Printf("Open: %t, GST: 5%%\n", open)
    total := 102.5
    fmt.Printf("%p\n", &total)
}

One real run (the last line, an address, will be different on your machine):

255 11111111 377 ff FF
420 644
1428600000.000000
1.428600e+09
1.43e+09
Open: true, GST: 5%
0xc00008c080
  • %b = binary (base 2, digits 0-1): 255 = 11111111.
  • %o = octal (base 8, digits 0-7): 377.
  • %x / %X = hexadecimal (base 16, digits 0-9 and a-f): ff / FF. Hex is common for colours (#ff8800), memory addresses and byte values.
  • 0644 with a leading zero is an octal literal: a whole number written in base 8 (Go also accepts the clearer 0o644). Its decimal value is 420, but Linux file permissions are always written in octal, so %o prints 644 (owner read+write, everyone else read). Episode 34 uses them for real files.
  • %e = scientific notation: 1.428600e+09 means 1.4286 × 10⁹. %.2e keeps 2 decimals: 1.43e+09.
  • %t = a bool as true or false.
  • %% prints one literal percent sign (a lone % would start a verb).
  • %p = a pointer: the memory address a pointer holds (episode 11), in hex with 0x in front. Go doesn't promise where a variable lives, so the number can differ between machines and runs: never rely on it. Use %p only to check whether two pointers point to the same place.

A few more verbs and flags worth knowing

package main

import "fmt"

func main() {
    fmt.Printf("%c %U %x\n", 'A', 'A', "chai")
    fmt.Printf("%+d %+d\n", 5, -5)
    fmt.Printf("[%8.3f] [%-8.1f] [%08.2f]\n", 3.14159, 3.14159, 3.14159)
    fmt.Printf("[%6s] [%.3s]\n", "chai", "samosa")
    fmt.Printf("%v %v\n", []string{"a", "b"}, map[string]int{"chai": 20})
    fmt.Printf("%g %g\n", 37.5, 1428600000.0)
    fmt.Println(fmt.Sprint("chai", 20, 30), fmt.Sprintln("chai", 20))
}
A U+0041 63686169
+5 -5
[   3.142] [3.1     ] [00003.14]
[  chai] [sam]
[a b] map[chai:20]
37.5 1.4286e+09
chai20 30 chai 20

Verb / flag Meaning
%c the character for a rune (episode 17)
%U Unicode code point, U+0041
%x on a string each byte in hex: "chai" → 63686169
%+d always show the sign
%.3s precision on a string cuts it to 3 characters
%g the shortest of %f and %e style, with no extra zeros
fmt.Sprint, fmt.Sprintln like Print / Println, but return a string (Sprintln keeps the newline, hence the blank line)

%q shows hidden characters

A customer typed chai, but with two spaces in front and a tab after it. Raju's menu lookup fails and he can't see why.

package main

import "fmt"

func main() {
    typed := "  chai\t"
    fmt.Printf("[%s]\n", typed)
    fmt.Printf("%q\n", typed)
    fmt.Printf("%q\n", "Raju's \"special\"")
}
[  chai ]
"  chai\t"
"Raju's \"special\""
  • %q prints a quoted string, Go syntax: double quotes around it, and invisible characters written as escape sequences (\t tab, \n newline). Quotes inside get a backslash: \".
  • Whenever text "looks right but doesn't match", print it with %q. strings.TrimSpace (practice 3) removes the extra spaces.

Verb mistakes, and go vet

package main

import "fmt"

func main() {
    fmt.Printf("%d cups of %s\n", "chai", 2)
    fmt.Printf("%s costs %d\n", "samosa")
    fmt.Printf("Total\n", 105)
}

It compiles and runs. Printf writes the problem into your output:

%!d(string=chai) cups of %!s(int=2)
samosa costs %!d(MISSING)
Total
%!(EXTRA int=105)
Output Meaning
%!d(string=chai) the verb %d got a value of the wrong type: string "chai"
%!d(MISSING) a verb with no value left for it
%!(EXTRA int=105) a value with no verb for it

go vet (episode 2), the "second doctor", checks every Printf-style call against its values. Real output of go vet main.go:

# command-line-arguments
# [command-line-arguments]
./main.go:6:5: fmt.Printf format %d has arg "chai" of wrong type string
./main.go:7:5: fmt.Printf format %d reads arg #2, but call has 1 arg
./main.go:8:15: fmt.Printf call has arguments but no formatting directives
  • A formatting directive is just another name for a verb.
  • vet reports the first wrong verb in a call (line 6's %s with 2 is also wrong; it is reported after you fix %d).
  • Run go vet before you share code. go test runs this check automatically (episode 40).

Sprintf builds a string

Raju wants to send the bill as an SMS. He doesn't want it printed; he wants a string to hand to an SMS service.

package main

import "fmt"

func main() {
    name, amt := "Asha", 102.5
    sms := fmt.Sprintf("Hi %s, bill of Rs %.2f paid.", name, amt)

    fmt.Println(len(sms), "characters")
    fmt.Println(sms)
}
32 characters
Hi Asha, bill of Rs 102.50 paid.
  • fmt.Sprintf ("S" for string) works exactly like Printf but returns the formatted text instead of printing it. Use it to build messages, file names, keys, log lines.
  • Nothing is printed until you choose to print it.
  • Related: fmt.Errorf builds an error the same way (episode 24).

The three standard streams

A canteen has three windows: orders come in at one, food goes out at another, and complaints ring a separate bell. Every program gets three channels from the operating system, called the standard streams:

Canteen Stream In Go Usually connected to
The order window standard input (stdin) os.Stdin the keyboard (or the compiler's input box)
The serving counter standard output (stdout) os.Stdout the screen
The complaint bell standard error (stderr) os.Stderr the screen, separately
  • Everything Println and Printf print goes to standard output.
  • Standard error is for warnings and error messages. Both reach the screen, but they are separate, so you can save the bill to a file and still see the warnings: go run main.go > bill.txt sends only stdout to the file.
  • A stream is a flow of bytes you read or write in order, from start to end.

Fprintf: choose where to write

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Fprintf(os.Stdout, "Bill: Rs %.2f\n", 102.5)
    fmt.Fprintf(os.Stderr, "warning: milk low, %d litres left\n", 2)
    fmt.Println("Thank you, visit again")
}

Standard output:

Bill: Rs 102.50
Thank you, visit again

Standard error (the SyntaxPilot compiler shows it in a separate Runtime errors box, even though the program finished normally):

warning: milk low, 2 litres left
  • fmt.Fprintf(w, format, values...) ("F" for file) is Printf with one extra first argument: where to write.
  • fmt.Fprintln(w, ...) is the same idea for Println. In fact fmt.Println(x) is just fmt.Fprintln(os.Stdout, x).

io.Writer: a first look

Fprintf's first parameter has the type io.Writer: anything you can write bytes to. os.Stdout, os.Stderr, an open file, a network connection and a strings.Builder are all writers. So one function can print a bill to the screen or into a string:

package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

func printTotal(w io.Writer, total float64) {
    fmt.Fprintf(w, "Total: Rs %.2f\n", total)
}

func main() {
    printTotal(os.Stdout, 102.5)

    var sb strings.Builder
    printTotal(&sb, 102.5)
    fmt.Printf("%q\n", sb.String())
}
Total: Rs 102.50
"Total: Rs 102.50\n"

How a type "counts as" an io.Writer is an interface: episodes 21 and 22. Episode 33 tours io and bufio in depth.

Reading input with fmt.Scan

Every bill so far had its numbers typed into the code. Now the customer types the order.

package main

import "fmt"

func main() {
    var qty int
    var rate float64
    n, err := fmt.Scan(&qty, &rate)
    fmt.Println(n, err)

    fmt.Printf("Total: Rs %.2f\n", float64(qty)*rate)
}

Program input box:

3 12.5
2 <nil>
Total: Rs 37.50
  • fmt.Scan(&a, &b, ...) reads values from standard input, separated by spaces, and stores them in the variables, converting text to each variable's type.
  • It needs the address of each variable (&qty, the address-of operator from episode 11) so it can write into it.
  • It returns n, how many values it filled, and err, an error value: nil (printed <nil>) when everything worked.
  • Scan treats newlines like spaces: input 3, Enter, 12.5 gives exactly the same result.

Now the customer types a word instead of a number:

three 12.5
0 expected integer
Total: Rs 0.00

Scan read nothing (n is 0) and err says expected integer. If you ignore err, the variables keep their zero values and the bill says Rs 0.00. Always check the error:

if err != nil {
    fmt.Println("please type a number:", err)
    return
}

Scan stops at spaces

package main

import "fmt"

func main() {
    var item string
    var qty int
    n, err := fmt.Scan(&item, &qty)
    fmt.Printf("%d %q %d %v\n", n, item, qty, err)
}
Program input box Output
samosa 3 2 "samosa" 3 <nil>
masala chai 2 1 "masala" 0 expected integer

Scan reads a string only up to the first space. item became "masala", then Scan tried to read chai as the number. Scan reads words, not lines.

Scanln stops at the end of the line

fmt.Scanln ("scan line") is like Scan but stops at a newline: all the values must be on one line, and it never wanders into the next line.

package main

import "fmt"

func main() {
    var item string
    var qty int
    n, err := fmt.Scanln(&item, &qty)
    fmt.Printf("%d %q %d %v\n", n, item, qty, err)
}
Program input box Output
samosa (Enter) 3 1 "samosa" 0 unexpected newline
samosa 3 2 "samosa" 3 <nil>

Scanln still splits at spaces, so masala chai is still a problem. We need to read a whole line.

bufio.Scanner: whole lines until EOF

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    count := 0
    for sc.Scan() {
        line := sc.Text()
        count++
        fmt.Printf("%d: %q\n", count, line)
    }
    fmt.Println(count, "lines, then EOF")
}

Program input box:

masala chai
 samosa 
bun maska
1: "masala chai"
2: " samosa "
3: "bun maska"
3 lines, then EOF
  • The bufio package ("buffered I/O") reads input through a buffer: a chunk of memory filled in large pieces, so reading is fast even for big inputs.
  • bufio.NewScanner(os.Stdin) makes a Scanner that reads from standard input. By default it splits the input into lines.
  • sc.Scan() moves to the next line and returns true, or false when there is no more input (or an error).
  • sc.Text() returns the current line as a string, without the newline. Spaces are kept exactly (%q shows " samosa ").
  • EOF = end of file: the point where input runs out. For a file it's the end of the file; for the compiler's input box, the end of the text; at a real terminal, you signal it with Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows). At EOF Scan returns false and the for loop ends by itself.
  • After the loop, check sc.Err(): it is nil at a normal EOF, and holds the error if reading failed (practice 3 shows it).
  • A Scanner's default maximum line length is 64 KB (bufio.MaxScanTokenSize); longer lines need sc.Buffer(...) (episode 33).
  • fmt.Scan also reports EOF: when input runs out it returns the error EOF (practice 2 shows stopped: EOF).

os.Args: command-line arguments

Another way to give a program input is when you start it. Words typed after the program name are command-line arguments, and Go puts them in os.Args, a []string.

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(len(os.Args))
    fmt.Println(os.Args[1:])

    if len(os.Args) < 3 {
        fmt.Println("usage: go run main.go QTY ITEM")
        return
    }
    fmt.Printf("Order: %s x %s\n", os.Args[2], os.Args[1])
}

In the SyntaxPilot compiler (no arguments are passed, only the program itself):

1
[]
usage: go run main.go QTY ITEM

In a real terminal:

$ go run main.go 2 chai
3
[2 chai]
Order: chai x 2
$ go run main.go 2 "masala chai"
3
[2 masala chai]
Order: masala chai x 2
  • os.Args[0] is always the program's own name or path. The real arguments start at os.Args[1].
  • Arguments are always strings: convert with strconv.Atoi when you need a number.
  • The shell splits arguments at spaces; put quotes around "masala chai" to keep it as one argument.
  • Always check len(os.Args) before indexing, or a missing argument panics with index out of range.
  • What os.Args[0] looks like, from a real terminal:
package main

import (
    "fmt"
    "os"
)

func main() {
    for i, a := range os.Args {
        fmt.Printf("os.Args[%d] = %q\n", i, a)
    }
}
$ go build -o order main.go
$ ./order 2 "masala chai"
os.Args[0] = "./order"
os.Args[1] = "2"
os.Args[2] = "masala chai"
$ go run main.go 2 chai
os.Args[0] = "/tmp/go-build2485854260/b001/exe/main"
os.Args[1] = "2"
os.Args[2] = "chai"

go run builds the program into a temporary folder first, so os.Args[0] is a temporary path (it differs every time). For flags like -qty=2, the standard flag package parses os.Args for you.

Mini project: a bill from typed orders

Each input line is item,quantity,rate.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    total := 0.0
    for sc.Scan() {
        f := strings.Split(sc.Text(), ",")
        qty, _ := strconv.Atoi(f[1])
        rate, _ := strconv.ParseFloat(f[2], 64)
        amt := float64(qty) * rate
        total += amt
        fmt.Printf("%-12s %3d %8.2f\n", f[0], qty, amt)
    }
    fmt.Printf("%-16s %8.2f\n", "Total", total)
}

Program input box:

masala chai,3,12.5
samosa,2,15
bun maska,1,35
masala chai    3    37.50
samosa         2    30.00
bun maska      1    35.00
Total              102.50
  • strings.Split(s, ",") cuts a string at every comma and returns a []string: ["masala chai" "3" "12.5"].
  • strconv.Atoi converts text to an int; strconv.ParseFloat(s, 64) converts text to a float64 (episode 4).
  • _, the blank identifier (episode 3), throws away their errors here only to keep the demo short. Real code checks them, and checks len(f) == 3 before using f[2].
  • Try it: add the header row from the width section, and a GST 5% line (remember %%).

The next problem: each order is three loose values (a name, a quantity, a rate) that we keep passing around together. Episode 19 gives them one name: a struct type.

Common mistakes (and the real messages)

You wrote Real error / what happens Fix
fmt.Printf("%d cups\n", "chai") output %!d(string=chai) cups; vet: fmt.Printf format %d has arg "chai" of wrong type string use %s (or %v)
fmt.Printf("%s costs %d\n", "samosa") output samosa costs %!d(MISSING); vet: fmt.Printf format %d reads arg #2, but call has 1 arg one value per verb
fmt.Printf("Total\n", 105) output %!(EXTRA int=105); vet: fmt.Printf call has arguments but no formatting directives add a verb, or use Println
fmt.Printf("Total: %d\n", 102.5) output Total: %!d(float64=102.5); vet: fmt.Printf format %d has arg 102.5 of wrong type float64 %.2f for floats
fmt.Printf("hi") twice hihi on one line end the format with \n
fmt.Printf("GST 5%\n") output GST 5%! then (MISSING) on the next line 5%%
fmt.Scan(&qty, &rate) ignoring err input three 12.5 → 0 expected integer, bill Rs 0.00 if err != nil { ... }
fmt.Scan(&item) for masala chai item is "masala" bufio.NewScanner(os.Stdin)
fmt.Scan(qty) (no &) no value is stored; err is type not a pointer: int pass &qty
os.Args[1] with no arguments panic: runtime error: index out of range [1] with length 1 check len(os.Args) first
relying on %p output the address differs between runs and machines compare pointers with ==

The last rows were checked with real runs too:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Printf("Total: %d\n", 102.5)
    fmt.Printf("GST 5%\n")
    var qty int
    _, err := fmt.Scan(qty)
    fmt.Println(err)
    fmt.Println(os.Args[1])
}

Program input box: 3

Total: %!d(float64=102.5)
GST 5%!
(MISSING)type not a pointer: int
panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
main.main()
    /tmp/.../main.go:14 +0x15e
exit status 2

Notice the GST line: the lone % took the newline character as its "verb", found no value for it, and printed %! + the newline + (MISSING). The real newline was used up, so the next output (type not a pointer: int) joined that line. go vet reports the first two lines:

./main.go:9:5: fmt.Printf format %d has arg 102.5 of wrong type float64
./main.go:10:5: fmt.Printf format %
 has unknown verb 

(The newline inside vet's second message is the "unknown verb" itself.)

Practice

  1. Print a train ticket table with three trains: name left-aligned in 10 characters, station left-aligned in 8, fare right-aligned with 2 decimals in 10.
  2. Read numbers with fmt.Scan until the input ends (or a non-number appears), then print how many and their average with 2 decimals.
  3. Read lines with bufio.Scanner; print each line with %q, its trimmed version with %q, and the trimmed length. Check sc.Err() at the end.
  4. Greet the name given in os.Args[1], or "guest" if there is none.
Solutions

1.

package main

import "fmt"

func main() {
    trains := []string{"Rajdhani", "Shatabdi", "Duronto"}
    from := []string{"Delhi", "Delhi", "Mumbai"}
    fares := []float64{2450, 1385.5, 1890.75}

    fmt.Printf("%-10s %-8s %10s\n", "Train", "From", "Fare")
    for i := range trains {
        fmt.Printf("%-10s %-8s %10.2f\n", trains[i], from[i], fares[i])
    }
}
Train      From           Fare
Rajdhani   Delhi       2450.00
Shatabdi   Delhi       1385.50
Duronto    Mumbai      1890.75
  1. The loop stops at the first error: EOF at the end of input, or expected integer for a word.
package main

import "fmt"

func main() {
    sum, count := 0, 0
    for {
        var n int
        _, err := fmt.Scan(&n)
        if err != nil {
            fmt.Println("stopped:", err)
            break
        }
        sum += n
        count++
    }
    if count > 0 {
        fmt.Printf("%d numbers, average %.2f\n", count, float64(sum)/float64(count))
    }
}

Input 10 20 30:

stopped: EOF
3 numbers, average 20.00

Input 10 20 (Enter) 30 abc:

stopped: expected integer
3 numbers, average 20.00

3.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    for sc.Scan() {
        line := sc.Text()
        clean := strings.TrimSpace(line)
        fmt.Printf("%q -> %q (%d chars)\n", line, clean, len(clean))
    }
    if err := sc.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "read error:", err)
    }
}

Input: chai, samosa, and an empty line:

"  chai " -> "chai" (4 chars)
"samosa" -> "samosa" (6 chars)
"" -> "" (0 chars)

4.

package main

import (
    "fmt"
    "os"
)

func main() {
    name := "guest"
    if len(os.Args) > 1 {
        name = os.Args[1]
    }
    fmt.Printf("Namaste, %s!\n", name)
}
$ go run main.go
Namaste, guest!
$ go run main.go Raju
Namaste, Raju!

Quick quiz

What does this print?

func main() {
    fmt.Printf("[%-5s|%5.1f]\n", "tea", 3.14159)
}
  • A. [ tea|3.1 ]
  • B. [tea | 3.1]
  • C. [tea|3.14159]
  • D. [tea |3.14 ]
Answer

B. [tea | 3.1]. %-5s pads "tea" on the right to 5 characters (left-aligned). %5.1f rounds to one decimal, 3.1, and pads on the left to 5 characters (right-aligned).

Interview questions

  • What is the difference between Print, Println and Printf? Which ones add spaces or a newline?
  • What do %v, %+v, %#v and %T print for a struct?
  • How do you print a float with exactly two decimals in a column 8 characters wide? Left-aligned?
  • What does %!d(MISSING) mean? How can you catch these mistakes before running the program?
  • What is the difference between Printf, Sprintf and Fprintf? What type is Fprintf's first argument?
  • What are stdin, stdout and stderr? Why write warnings to stderr?
  • Why does fmt.Scan need &x? What does it return?
  • How do you read a full line that contains spaces? How does the loop know when input has ended?
  • What is in os.Args[0]? What type are the arguments?

Glossary

Term Meaning Example
fmt Go's package for formatted input and output import "fmt"
fmt.Print prints values with no newline; spaces only between two non-strings Items:3 2
fmt.Println prints values with spaces between them and a newline at the end masala chai 3 37.5
fmt.Printf prints a format string with its verbs filled in; no automatic newline fmt.Printf("%d\n", 3)
Format string a template: fixed text plus verbs "%s x %d = %.2f\n"
Verb (formatting directive) a placeholder starting with % saying how to show a value %d, %s
\n the newline escape sequence "Total\n"
Escape sequence a backslash code for a special character \t tab, \" quote
%v a value in its default format {samosa 3 false}
%+v like %v, plus struct field names {item:samosa qty:3 paid:false}
%#v the value as Go syntax []int{4, 7}
%T the type of a value main.order, []int
%d an integer in decimal (base 10) 255
%b an integer in binary (base 2) 11111111
%o an integer in octal (base 8) 377, 644
%x / %X hexadecimal (base 16), lower / upper case ff / FF
%s a string masala chai
%q a quoted string with escapes, showing hidden characters " chai\t"
%f a float with 6 decimals by default 37.500000
%e a float in scientific notation 1.428600e+09
%g a float in the shortest form 37.5
%t a bool true
%p a pointer: a memory address in hex 0xc00008c080 (varies)
%c / %U a rune as a character / as a code point A / U+0041
%% a literal percent sign GST: 5%
Width minimum characters for a value; the number before the dot %8.2f → 8
Precision decimals for a float (or max characters for a string); after the dot %8.2f → 2
Padding spaces (or zeros) added to fill the width [ 42]
Alignment which side of its width a value sits %-12s left, %8.2f right
- flag left-align [42 ]
0 flag pad with zeros %05d → 00042
+ flag always print the sign %+d → +5
%!d(string=chai) Printf's report of a verb given the wrong type wrong verb
%!d(MISSING) a verb with no value too few values
%!(EXTRA ...) a value with no verb too many values
go vet a tool that finds suspicious code, including bad Printf calls go vet main.go
Binary / octal / hexadecimal writing numbers in base 2 / 8 / 16 255 = 11111111 = 377 = ff
Octal literal an integer written with a leading 0 0644 = 420
File permission who may read/write/run a file, written in octal 644
Scientific notation a number as digits × a power of ten 1.43e+09
Floating-point approximation a float stores the closest binary value, not the exact decimal 0.30000000000000004
fmt.Sprintf like Printf, but returns the string sms := fmt.Sprintf(...)
fmt.Sprint / Sprintln like Print / Println, but return a string fmt.Sprint("chai", 20)
fmt.Fprintf like Printf, writing to a chosen writer fmt.Fprintf(os.Stderr, ...)
fmt.Fprintln like Println, writing to a chosen writer fmt.Fprintln(os.Stderr, "read error:", err)
Stream a flow of bytes read or written in order standard output
Standard streams the three streams every program gets stdin, stdout, stderr
Standard input (stdin) where a program reads input; the keyboard or input box os.Stdin
Standard output (stdout) where normal output goes os.Stdout
Standard error (stderr) where warnings and errors go, separate from stdout os.Stderr
os.Stdin / os.Stdout / os.Stderr Go's values for the three streams bufio.NewScanner(os.Stdin)
io.Writer the type of anything you can write bytes to (interface, episode 22) os.Stdout, &sb
strings.Builder a writer that collects text into a string sb.String()
fmt.Scan reads space- or newline-separated values from stdin into variables fmt.Scan(&qty, &rate)
fmt.Scanln like Scan, but stops at the end of the line unexpected newline
& (address-of) gives a variable's address so a function can write into it &qty
n, err Scan's results: how many values were filled, and an error 2 <nil>
error / nil a value describing what went wrong; nil means nothing did expected integer
Zero value the value a variable has before anything is stored 0, ""
bufio the buffered I/O package bufio.NewScanner
Buffer memory that holds data read in large chunks inside a Scanner
bufio.Scanner reads input piece by piece, by default one line at a time sc := bufio.NewScanner(os.Stdin)
sc.Scan() moves to the next line; false at EOF or error for sc.Scan() { ... }
sc.Text() the current line, without its newline "masala chai"
sc.Err() the reading error after the loop, nil at a normal EOF if err := sc.Err(); err != nil
EOF end of file: input has run out Ctrl+D at a terminal
Command-line arguments words typed after the program name when starting it go run main.go 2 chai
os.Args a []string: program name, then the arguments [program 2 chai]
os.Args[0] the program's own name or path ./order
Struct / field a value made of named fields (episode 19) order{"samosa", 3, false}
strings.Split cuts a string at a separator into a []string strings.Split("a,b", ",")
strings.TrimSpace removes spaces, tabs and newlines at both ends " chai " → "chai"
strconv.Atoi converts text to an int strconv.Atoi("3")
strconv.ParseFloat converts text to a float64 strconv.ParseFloat("12.5", 64)
Blank identifier _ throws away a value you don't need qty, _ := strconv.Atoi(...)

Summary

  • Print and Println print values as they are; Printf fills a format string, and each verb (%s %d %f %t %q %v ...) says how to show one value.
  • Width and precision make columns: %-12s (left), %3d, %8.2f (right), %05d (zeros).
  • %v, %+v, %#v, %T are for debugging; %b %o %x show other bases; %e scientific; %p an address; %% a percent sign; %q reveals hidden spaces.
  • Wrong verbs still compile: %!d(string=chai), %!d(MISSING), %!(EXTRA ...). go vet catches them.
  • Sprintf returns a string; Fprintf writes to any io.Writer, such as os.Stdout or os.Stderr.
  • Every program has three standard streams: stdin, stdout, stderr.
  • fmt.Scan reads words (needs &x, returns n, err); Scanln stops at the end of a line; bufio.Scanner reads whole lines until EOF.
  • os.Args holds the program name and the command-line arguments, all strings.

Next episode: structs and type declarations: struct types, fields, keyed and positional literals, anonymous and nested structs, comparing and copying structs, exported fields, and defined types.