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

Interpreted String Literals

Interpreted String Literals 10 minA double-quoted string literal is interpreted: backslash escapes such as \n, \t, \" and \u00e9 are turned into the characters they stand for, and the literal must fit on one line.

golang / Interpreted String Literals

Explore each scene at your own pace.

01 · The rule

The rule

Interpreted String Literals

A double-quoted string literal is interpreted: backslash escapes such as \n, \t, \" and \u00e9 are turned into the characters they stand for, and the literal must fit on one line.

Inspect escape sequences and the bytes they contribute to a string.

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 \n inside 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.

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