什么是;使用Go语法“安全逃逸”;什么意思?

什么是;使用Go语法“安全逃逸”;什么意思?,go,escaping,string-formatting,Go,Escaping,String Formatting,Go的包将%q(用于字符串)定义为: 它还有别的作用吗?在什么情况下,您可能希望使用此选项?我猜可能是在生成Go代码的模板中?这意味着格式化输出将正确转义,可以复制并在Go源代码中使用 示例格式化 "abc" => `"abc"` []byte("abc") => `"abc"` "" => `""` "\"" => `"\""` `\n` => `"\\n"` rena

Go的包将
%q
(用于字符串)定义为:


它还有别的作用吗?在什么情况下,您可能希望使用此选项?我猜可能是在生成Go代码的模板中?

这意味着格式化输出将正确转义,可以复制并在Go源代码中使用

示例格式化

 "abc"          => `"abc"`
 []byte("abc")  => `"abc"`
 ""             => `""`
 "\""           => `"\""`
 `\n`           => `"\\n"`
 renamedBytes([]byte("hello")) => `"hello"`
 []renamedUint8{'h', 'e', 'l', 'l', 'o'} => `"hello"`
 reflect.ValueOf("hello") => `"hello"`
解释上述内容的代码

package main

import (
    "fmt"
    "reflect"
)

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

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

它将奇怪/格式错误的输入转换为可以安全使用的内容

它将更改此字节数组的字符串表示形式
[]字节{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}来自“请检查答案,如果有帮助,请接受。@SarathSadasivanPillai虽然我本人没有对这个问题进行否决,但如果您将鼠标悬停在“否决”按钮上,您将在工具提示中看到“默认推理”,因此如果否决者没有提供任何详细信息,您可以,如果您愿意,假设为默认值。这是一个示例“renamedBytes”,它是从字节派生的类型。键入renamedBytes[]bytes并尝试此操作,因为在我的示例中是一个以字符串表示的字节数组,字节数组是[]字节{56、21、114、215、252、199、62、146、143、167、197、162、172、158、112、4、76、17222、32、34215、199、97187、143、61161、211、96198、218、134、106、85107162、194、36153、255}我会将其编辑到我的回答中,不一定是“奇怪/畸形”。正如问题的例子所示,它可以只包含引号。
 "abc"          => `"abc"`
 []byte("abc")  => `"abc"`
 ""             => `""`
 "\""           => `"\""`
 `\n`           => `"\\n"`
 renamedBytes([]byte("hello")) => `"hello"`
 []renamedUint8{'h', 'e', 'l', 'l', 'o'} => `"hello"`
 reflect.ValueOf("hello") => `"hello"`
package main

import (
    "fmt"
    "reflect"
)

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

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