Skip to the workspace
Pebellslearn by building
Strings and Type Conversion  ›  Lesson

Raw String Literals

Raw String Literals 10 minA raw string literal uses backticks and does not interpret backslash escapes. It may span lines, but cannot contain a backtick and discards carriage-return characters.

golang / Raw String Literals

Explore each scene at your own pace.

01 · The rule

The rule

Raw String Literals

A raw string literal uses backticks and does not interpret backslash escapes. It may span lines, but cannot contain a backtick and discards carriage-return characters.

Compare raw text with interpreted escapes when representing paths or multiline content.

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 regexp with its backslashes intact. The double-quoted version would be "\\b\\w+\\b".

What "raw" means precisely:

  • \n inside backticks is two characters, a backslash and an n, so len(`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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.