Raw String Literals
tally needs a help message several lines long, and a regular expression full of backslashes. Writing either with double quotes means a thicket of \n and \\. Go has a second kind of literal that simply takes you at your word.
The rule
Backticks are raw: what you type is exactly what you get.
A string between backticks is a raw literal. No escape sequences are processed, and it may span as many lines as you like:
const usage = `tally counts the words in a file.
Usage:
tally [-v] FILE
`
var wordPattern = regexp.MustCompile(`\b\w+\b`)- The help text keeps its real line breaks and tab.
- The pattern reaches
regexpwith its backslashes intact. The double-quoted version would be"\\b\\w+\\b".
What "raw" means precisely:
\ninside backticks is two characters, a backslash and ann, solen(`a\nb`)is 4, not 3.- Line breaks you type are kept as newline characters.
- Carriage returns (
\r) are dropped, so a file saved with Windows line endings still gives the same string. - A raw string cannot contain a backtick, because that ends it. Join a piece in double quotes instead:
`say ` + "`hi`".
Because nothing is processed, a raw string is always exactly as long as the characters you typed, minus any carriage returns. That makes it easy to reason about, and it is why tools that generate Go code often emit raw strings for embedded text.
Raw strings shine for help text, regular expressions, Windows paths such as `C:\notes\new.txt`, SQL queries, and JSON samples in tests.
The shortcut
Choose by asking "does my text contain backslashes or line breaks I want kept?" Yes → backticks. "Do I need a tab, newline or quote produced by an escape?" Yes → double quotes.
The help message
Several lines, laid out by hand. Backticks, typed as it should look.
Drills
Answer fast — trust the rule.
How many bytes long is the raw literal `tab\t`?
Which literal produces the regular expression \d+ correctly?
Which character can a raw string literal not contain?
A raw literal typed over three lines is printed. What do you see?
Remember
- Backticks are raw: what you type is exactly what you get.
- Shortcut: backslashes or hand-laid lines → backticks; escapes wanted → double quotes.
- Trap:
\nin backticks is two characters, and a backtick cannot go inside.
