Go Reference ยท strings and strconv
Go strconv.Quote() and Unquote()
Reference for Go strconv.Quote, QuoteToASCII, QuoteRune and Unquote: produce safe double-quoted Go literals with escapes and parse them back, with error cases.
strconv.Quote returns a double-quoted Go string literal for a string, escaping quotes, backslashes, control characters and unprintable runes. strconv.Unquote does the reverse: it takes a quoted literal and returns the text it stands for.
Quoting is how you make invisible characters visible in logs and error messages, and how you serialize strings in a format that Go itself could read back. It is what the %q verb in fmt uses.
q := strconv.Quote("say \"hi\"\n") // "say \"hi\"\n" (with the quotes and backslashes shown)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Quote(s string) string func QuoteToASCII(s string) string func QuoteRune(r rune) string func QuoteRuneToASCII(r rune) string func Unquote(s string) (string, error) func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
| Name | Description |
|---|---|
s |
For Quote*: any string. For Unquote: a complete quoted literal. |
r |
A rune for QuoteRune and QuoteRuneToASCII; the result uses single quotes. |
quote |
The delimiter character used by UnquoteChar. |
Returns: Quote yields a double-quoted string using \n, \t, \", \\, \xNN for invalid bytes and \uNNNN for unprintable runes. QuoteToASCII also escapes every non-ASCII rune as \uNNNN. Unquote returns the decoded text.
Errors: Unquote returns strconv.ErrSyntax (and an empty string) when s lacks matching quotes, has an unterminated literal, contains an invalid escape, or has trailing text after the closing quote.
Usage notes
Unquoteunderstands three forms: double-quoted ("...", with escapes), backquoted raw strings (`...`, no escapes) and single-quoted single characters ('x').- Printable Unicode is kept by
Quote(theรฉandโบstay as they are). UseQuoteToASCIIwhen the output must be pure ASCII. - Invalid UTF-8 survives. Bytes that are not valid UTF-8 appear as
\xNN, which makesQuotegood for debugging binary-ish data. - Prefer
%qinfmtfor one-off logging; useQuotewhen you need the string itself. - Not JSON. Go literals use
\xand\a, which JSON does not allow. Useencoding/jsonto produce JSON strings. - Single-quoted
Unquoteaccepts only one character:'xy'is a syntax error.