go - “使用 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 代码的模板中?
解决方案
这意味着格式化的输出将被正确转义,以便可以在 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"))
}
推荐阅读
- r - 如何在 `mutate_at` 中应用一个函数,以按行对其他列中的值进行条件?
- javascript - jQuery Autocomplete,不同的来源取决于输入的字符
- python - 尝试在 Databricks 环境中合并或合并两个 pyspark.sql.dataframe.DataFrame
- asp.net - AspNetCore 上 localhost 的 CORS 策略阻止
- excel - 使用 DAX 寻找下一个工作日
- swift - 尝试将占位符值插入 CoreData 时避免意外更新
- c# - 扫描二维码时显示 Json 列表中的项目
- ios - 我没有在我的 iOS 应用程序中收到推送通知 Firebase
- excel - 指定命令行的 VBA 脚本问题
- flutter - 在颤动中更改时如何停止高程动画?