I tried playing around a bit and found that sample and sample[0] give a different output as below. I know a UTF-8 encoded Unicode character one-half should be “\xc2\xbd”, so the output of sample makes more sense to me. Can anyone help me understand why printing out a single byte produces the correct UTF-8 encoded character?
package main
import "fmt"
func main() {
var sample = "\xbd"
fmt.Println("Println:")
fmt.Println(sample)
fmt.Printf("%q, %q\n", sample, sample[0])
}```
Wait, I don’t quite understand what your question is? Are you wondering why %q ?
%q a double-quoted string safely escaped with Go syntax
see : fmt/format.go
// fmtQ formats a string as a double-quoted, escaped Go string constant.
// If f.sharp is set a raw (backquoted) string may be returned instead
// if the string does not contain any control characters other than tab.
func (f *fmt) fmtQ(s string) {
s = f.truncateString(s)
if f.sharp && strconv.CanBackquote(s) {
f.padString("`" + s + "`")
return
}
buf := f.intbuf[:0]
if f.plus {
f.pad(strconv.AppendQuoteToASCII(buf, s))
} else {
f.pad(strconv.AppendQuote(buf, s))
}
}