“使用Go语法安全地转义”是什么意思?

Go's fmt package defines %q (for strings) as:

 %q      a double-quoted string safely escaped with Go syntax

What does safely escaped with Go syntax mean?

Some experimentation shows it preserves escape sequences used in the original string:

s := "This has \"quotes\" in it"
fmt.Printf("%q
", s)             // output: "This has \"quotes\" in it"

Is there anything else it does? In what situations might you want to use this? I'm guessing perhaps in templates that generate Go code?

It means that the formatted output would be escaped properly that it can be copied and used in the go source code

Example formattings

 "abc"          => `"abc"`
 []byte("abc")  => `"abc"`
 ""             => `""`
 "\""           => `"\""`
 `
`           => `"\
"`
 renamedBytes([]byte("hello")) => `"hello"`
 []renamedUint8{'h', 'e', 'l', 'l', 'o'} => `"hello"`
 reflect.ValueOf("hello") => `"hello"`

Code explaining the above

package main

import (
    "fmt"
    "reflect"
)

func main() {
    type renamedBytes []byte
    type renamedUint8 uint8

    fmt.Printf("%q
", "abc")
    fmt.Printf("%q
", []byte("abc"))
    fmt.Printf("%q
", "
")
    fmt.Printf("%q
", []renamedUint8{'h', 'e', 'l', 'l', 'o'})
    fmt.Printf("%q
", renamedBytes([]byte("hello")))
    fmt.Printf("%q
", reflect.ValueOf("hello"))
}

it transforms a strange / malformed input into something that is safe to use

it would change the string representation of this byte array []byte{56 ,21 ,114 ,215 ,252 ,199 ,62 ,146 ,143 ,167 ,197 ,162 ,172 ,158 ,112 ,4 ,76 ,17 ,222 ,32 ,34 ,215 ,199 ,97 ,187 ,143 ,61 ,161 ,211, 96 ,198 ,218 ,134 ,106 ,85 ,107 ,162 ,194 ,36 ,153, 255} from "o<�i���H���O��Ia)eb�?G(V���H" into "\x9d\xd8ջ\x90\xf13\x89\xd6\xd0\v2\xc0\xbe.m\xaa!B\xbf\xbe\xe7s\x0e\xff\xac\xf4Ӕ\xe6Dx\x88\xd3c\xa2P\x16n\x97\xc8"

but "hello world" would remain "hello world"

if the byte array is printer straight into your terminal it might make your terminal look weird, for example my terminal returned this " "D␊␌⎼≤⎻├␊␍ ⎽├⎼␋┼± "H␊┌┌⎺, ┬⎺⎼┌␍!", when i used string() instead of "%q"