Quote And Unquote With strconv

Escape arbitrary strings into safe double-quoted literals with strconv.Quote and recover them with Unquote, keeping control characters intact.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// 含换行与制表符的原始串
	raw := "line1\tvalue\nline2 \"quoted\"\""

	quoted := strconv.Quote(raw)
	fmt.Println("quoted:", quoted)

	back, err := strconv.Unquote(quoted)
	fmt.Println("unquote error:", err)
	fmt.Println("roundtrip ok:", back == raw)

	// QuoteToASCII 把非 ASCII 一并转义,输出可安全进入 ASCII 协议
	fmt.Println("ascii:", strconv.QuoteToASCII("naïve café"))

	// 非法字面量解不出:尾引号缺失直接报错
	_, err = strconv.Unquote("\"no closing")
	fmt.Println("bad literal:", err)
}

How the snippet works

raw’s literal spells \t, \n and \" — eight source characters that become a real tab, newline and quotes at runtime. strconv.Quote(raw) re-escapes that into a printable literal, and strconv.Unquote(quoted) reverses it; the roundtrip ok: line compares back == raw so any loss in the round trip would print false.

strconv.QuoteToASCII("naïve café") goes one step further and escapes the non-ASCII letters too, producing output safe for an ASCII-only protocol. The last statement feeds strconv.Unquote("\"no closing") — a literal missing its closing quote — and prints the returned error instead of panicking.

Points of care

  • Unquote requires a quoted literal (with surrounding quotes), not a bare escaped string; for bare escapes reach for strconv.UnquoteChar.
  • Concatenating raw into quotes by hand performs no escaping — the embedded newline would split the literal and fail to parse; that is exactly what Quote exists for.
  • The error from a malformed literal must be checked: fmt.Println("bad literal:", err) is the only reporting path in this file.

Using it

The primary signature is func main()

Output arrives with tags — quoted:, unquote error:, roundtrip ok: — when the file runs.

Key statements

_, err = strconv.Unquote("\"no closing")

Interactive Tools for This Topic

FAQ

What does Quote And Unquote With strconv print when run?
Execute the whole file; each printed line is prefixed with a label like `quoted:`, `unquote error:`, `roundtrip ok:`.