Escapes and multiline strings
Raw string literals
Raw string literals, delimited by backticks (back quotes), are interpreted literally. They can contain line breaks, and backslashes have no special meaning.
const s = `First line
Second line`
fmt.Println(s)
First line Second line
Backtick escape
It’s not possible to include a backtick in a raw string literal, but you can do
fmt.Println("`" + "foo" + "`") // Prints: `foo`
Interpreted string literals
To insert escape characters, use interpreted string literals delimited by double quotes.
const s = "\tFirst line\n" +
"Second line"
fmt.Println(s)
First line Second line
The escape character \t
denotes a horizontal tab and \n
is a line feed or newline.
Double quote escape
Use \"
to insert a double quote in an interpreted string literal:
fmt.Println("\"foo\"") // Prints: "foo"
Escape HTML
Use html.EscpapeString
to encode a string so that it can be safely placed inside HTML text.
The function escapes the five characters <
, >
, &
, '
and "
.
const s = `"Foo's Bar" <foobar@example.com>`
fmt.Println(html.EscapeString(s))
"Foo's Bar" <foobar@example.com>
html.UnescapeString
does the inverse transformation.
Escape URL
Use url.PathEscape
in package net/url
to encode a string so it can be safely placed inside a URL.
The function uses percent-encoding.
const s = `Foo's Bar?`
fmt.Println(url.PathEscape(s))
Foo%27s%20Bar%3F
url.PathUnescape
does the inverse transformation.
All escape characters
Arbitrary character values can be encoded with backslash escapes and used in string or rune literals. There are four different formats:
\x
followed by exactly two hexadecimal digits,\
followed by exactly three octal digits,\u
followed by exactly four hexadecimal digits,\U
followed by exactly eight hexadecimal digits,
where the escapes \u
and \U
represent Unicode code points.
The following special escape values are also available.
Value | Description |
---|---|
\a |
Alert or bell |
\b |
Backspace |
\\ |
Backslash |
\t |
Horizontal tab |
\n |
Line feed or newline |
\f |
Form feed |
\r |
Carriage return |
\v |
Vertical tab |
\' |
Single quote (only in rune literals) |
\" |
Double quote (only in string literals) |
fmt.Println("\\caf\u00e9") // Prints string: \café
fmt.Printf("%c", '\u00e9') // Prints character: é