Reading — step 1 of 5
Learn
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 output byte-for-byte, fluency here pays off on literally every exercise that follows.
The verbs that matter
The working set:
| verb | meaning | example output |
|---|---|---|
%d | integer, decimal | 42 |
%s | string | hello |
%f | float | 3.140000 |
%.2f | float, 2 decimals | 3.14 |
%t | bool | true |
%c | character (rune) | A |
%q | quoted string | "hello" |
%v | anything, default format | works on every type |
%T | the argument's type | []int |
%% | a literal percent sign | % |
Three of these are quiet superstars:
%vprints any value sensibly — slices as[1 2 3], maps asmap[a:1], structs as{Alice 30}. And%+vadds field names:{Name:Alice Age:30}. It's the universal debugging verb.%qwraps strings in quotes and shows escape characters — when output "looks right" but fails comparison,%qreveals the trailing\nor sneaky tab that%shides. Debugging tool of the course.%Tanswers "what type is this, actually?" — worth its weight when type errors confuse.
Width and precision
Numbers between % and the verb control layout:
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:
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
Printfdoes not add a newline.Printlndoes. Forgetting\nin a format string glues your output to the next line — and fails byte-exact tests. When output is "correct but on one line," this is why.- Verb/argument mismatch —
%dwith a string prints%!d(string=hi)right into your output. Go doesn't crash; it tells you inline, andgo vetcatches 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.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…