Tuesday, January 21, 2025
HomeGolangGo strings, utf-8 and byte slices - Getting Assist

Go strings, utf-8 and byte slices – Getting Assist


Hello peeps, I’m studying this Go weblog about strings: https://go.dev/weblog/strings

I attempted taking part in round a bit and located that pattern and pattern[0] give a special output as beneath. I do know a UTF-8 encoded Unicode character one-half ought to be “xc2xbd”, so the output of pattern makes extra sense to me. Can anybody assist me perceive why printing out a single byte produces the right UTF-8 encoded character?

bundle essential

import "fmt"

func essential() {
    var pattern = "xbd"

    fmt.Println("Println:")
    fmt.Println(pattern)
    fmt.Printf("%q, %qn", pattern, pattern[0])
}```

Wait, I don’t fairly perceive what your query is? Are you questioning why %q ?
%q a double-quoted string safely escaped with Go syntax

see : fmt/format.go

// fmtQ codecs a string as a double-quoted, escaped Go string fixed.
// If f.sharp is ready a uncooked (backquoted) string could also be returned as a substitute
// if the string doesn't comprise any management characters aside from 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))
	}
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments