Interpreted String Literals
tally prints a small report: a label, a tab, a number, a line break, then a file name in quotes. None of those characters are easy to type inside a string directly. Double-quoted literals solve this with escapes.
The rule
Double quotes interpret: every backslash starts an escape.
A string in "double quotes" is an interpreted literal. The compiler reads it and replaces each escape sequence with the character it stands for:
| Escape | Becomes |
|---|---|
\n |
new line |
\t |
tab |
\" |
a double quote |
\\ |
one backslash |
\u00e9 |
the character with that code point, é |
\x41 |
the byte 0x41, the letter A |
summary := "Words:\t17\nFile: \"notes.txt\""
fmt.Println(summary)
// Words: 17
// File: "notes.txt"Two rules follow:
- An interpreted literal must sit on one line. To break text across lines you write
\ninside it, or join pieces with+. - Every backslash is special. An unknown escape such as
"\d"is a compile error, and a known one in the wrong place changes your text silently:"C:\new"contains a newline, not\n.
Escapes are resolved at compile time, so they cost nothing at run time, and len counts the result: len("a\tb") is 3, one byte for the tab.
The shortcut
Read a double-quoted string left to right, and whenever you meet a backslash, swallow it with the next character and write down what the pair becomes.
Plain characters
W,o,r,d,s,:are copied as they are: 6 bytes.
Use the same pass to catch mistakes: if a pair is not in the table, either it is a compile error or you meant a real backslash, \\.
Rune literals in single quotes use the same escapes: '\n' is the newline rune and '\'' is a single quote. Inside a double-quoted string, though, a single quote needs no escape at all: "it's" is fine.
Drills
Answer fast — trust the rule.
How do you put a double quote inside a double-quoted string?
What is len("a\tb")?
What does fmt.Println("C:\new") print?
What happens with "\d+" as a Go string literal?
Remember
- Double quotes interpret: every backslash starts an escape.
- Shortcut: swallow each backslash with the next character and write down the result.
- Trap: paths and regular expressions full of backslashes — double them or use a raw string.
