du155305 2019-05-09 08:31
浏览 114

“使用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?

  • 写回答

2条回答 默认 最新

  • dsp1836 2019-05-09 08:39
    关注

    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"))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!