Escapes and multiline strings

yourbasic.org/golang
Amiga style ASCII art

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))
&#34;Foo&#39;s Bar&#34; &lt;foobar@example.com&gt;

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:

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: é

Share this page: