Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

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.

Decoding "Words:\t17\n"Step 1 of 4
  1. 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.

quick drill

How do you put a double quote inside a double-quoted string?

quick drill

What is len("a\tb")?

quick drill

What does fmt.Println("C:\new") print?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

Explaintally's summary line

tally prints a summary like: Words:17, then a new line, then File: "notes.txt". Write it as one double-quoted literal and explain each escape you used, and why "C:\new" would not mean what a Windows user expects.