当前位置: > > > > “用 Go 语法安全转义”是什么意思?
来源:stackoverflow
2024-04-29 10:00:38
0浏览
收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天给大家整理了《“用 Go 语法安全转义”是什么意思?》,聊聊,我们一起来看看吧!
问题内容
go 的 fmt
包将 %q
(对于字符串)定义为:
%q a double-quoted string safely escaped with go syntax
使用 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")) }
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《“用 Go 语法安全转义”是什么意思?》文章吧,也可关注公众号了解相关技术文章。