Skip to content
Lesson 5 of 14

Step 1 of 5 · Reading · ~3 min

Learn

Strings

Formatted Printing

fmt.Println gets you started; fmt.Printf is how programs actually talk. It's Go's version of the C printf family — a format string with verb placeholders, filled by the arguments that follow — and since graders (and log parsers, and users) compare the exact characters you print, fluency here pays off on literally every exercise that follows.

The verbs that matter

go

The working set:

verbmeaningexample output
%dinteger, decimal42
%sstringhello
%ffloat3.140000
%.2ffloat, 2 decimals3.14
%tbooltrue
%ccharacter (rune)A
%qquoted string"hello"
%vanything, default formatworks on every type
%Tthe argument's type[]int
%%a literal percent sign%

Three of these are quiet superstars:

  • %v prints any value sensibly — slices as [1 2 3], maps as map[a:1], structs as {Alice 30}. And %+v adds field names: {Name:Alice Age:30}. It's the universal debugging verb.
  • %q wraps strings in quotes and shows escape characters — when output "looks right" but fails comparison, %q reveals the trailing \n or sneaky tab that %s hides. Debugging tool of the course.
  • %T answers "what type is this, actually?" — worth its weight when type errors confuse.

Width and precision

Numbers between % and the verb control layout:

go

That's how tables line up and how "print with exactly two decimal places" — a constant refrain in graded exercises — is spelled: %.2f rounds (3.847 → 3.85), it doesn't truncate.

The family

Same verbs, three destinations:

go

Sprintf is the one people forget exists — any time you're tempted to build a string with + and conversions, Sprintf is cleaner: label := fmt.Sprintf("(%d, %d)", x, y).

The two classic mistakes

  1. Printf does not add a newline. Println does. Forgetting \n in a format string glues your output to the next line — and fails the comparison. When output is "correct but on one line," this is why.
  2. Verb/argument mismatch%d with a string prints %!d(string=hi) right into your output. Go doesn't crash; it tells you inline, and go vet catches most cases at build time. Read the noise; it names the verb and the type.

Your exercise — the greeting card — is a Printf composition test: fixed text, interpolated values, exact spacing, exact newlines. Sketch the expected output literally, then transcribe it into a format string verb by verb. That transcription skill is the whole lesson.

Up nextIf, Else, SwitchControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…