首页 > 解决方案 > “使用 Go 语法安全转义”是什么意思?

问题描述

Go 的fmt包定义%q(对于字符串)为:

%qa 双引号字符串使用 Go 语法安全转义

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

一些实验表明它保留了原始字符串中使用的转义序列:

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

它还有其他作用吗?在什么情况下你可能想使用它?我猜也许是在生成 Go 代码的模板中?

标签: goescapingstring-formatting

解决方案


这意味着格式化的输出将被正确转义,以便可以在 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"))
}

推荐阅读